package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;
import org.apache.struts.util.MessageResources;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.alarms.Alarm;
import com.scalar.chiptrack.alarms.AlarmUser;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.actions.InternalCommentsAction;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.packingslip.PackingSlipComparator;
import com.scalar.chiptrack.sales.*;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.CustomerRelationshipDAO;
import com.scalar.chiptrack.sales.dao.EndUserDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.forms.ApproverOrderForm;
import com.scalar.chiptrack.sales.forms.SalesOrderForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;

/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.28 $ $Date: 2011/03/01 16:59:06 $
 */

public final class ChangeOrderAction extends ChipTrackAction
{

    private static final String ACTION_NAME = "/changeOrder.do";


	public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
            throws Exception
    {

        SalesOrderForm subform = ( SalesOrderForm ) form;
        String action = request.getParameter ( "action" );
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        int isSample = 1; //default set to salesOrder
        if ( ( request.getParameter ( "isSample" ) != null ) && ( !request.getParameter ( "isSample" ).equals ( "null" ) ) )
        {
            isSample = Integer.parseInt ( request.getParameter ( "isSample" ) );
        }

        if ( user == null )
        {
            if( "printView".equals ( action ) )
            {
                request.setAttribute ( "closeWindowAfterSessionExp", "true" );
			    return ( mapping.findForward( "printView" ) );
            }
            else{
                 session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString ()+"&"+"isSample="+request.getParameter("isSample") );
                return ( mapping.findForward ( "login" ) );
            }
        }
        if ( user != null )
        {
            if ( isSample == 1  && user.isActionAllowed ( Functionality.SALES_CHANGE_ORDER, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else if ( isSample == 0  && user.isActionAllowed ( Functionality.SAMPLE_CHANGE_ORDER, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }
        //request.setAttribute ( "partNumberList", SalesOrderDAO.loadAllMarketingPartNumbers() );

        HashMap<String, String> errors = new HashMap<String, String> ();
        HashMap<String, String> info = new HashMap<String, String> ();
        String customerId = request.getParameter ( "customerId" );
        SalesOrder salesOrderFromMap = null;
        HashMap<String, SalesOrder>  salesOrderMap = ( HashMap<String, SalesOrder> ) session.getAttribute( "salesOrderMap" );
        if ( salesOrderMap == null )
        {
            salesOrderMap = new HashMap<String, SalesOrder>();
            session.setAttribute( "salesOrderMap", salesOrderMap );
        }
        if ( customerId != null )
        {
            try
            {
                if ( salesOrderMap != null )
                {
                    salesOrderFromMap = ( SalesOrder ) salesOrderMap.get( customerId );
                    if( salesOrderFromMap == null )
                    {
                        if ( action != null )
                        {
                            errors.put( ERROR_CHANGE_ORDER_ALREADY_SAVED_FOR_SAME_CUSTOMER, null );
                            request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                            action = null;
                        }
                        else
                        {
                            salesOrderFromMap = new SalesOrder();
                            salesOrderMap.put( customerId, salesOrderFromMap );
                        }
                    }
                    else
                    {
                        if ( subform.getOdmId() > 0 )
                        {
                            salesOrderFromMap.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) ) ;
                        }
                        else
                        {
                            salesOrderFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( subform.getCustomerId ()) ) ;
                        }
                    }
                }
            } catch( Exception e ){ e.printStackTrace() ; }
        } //END OF CUSTOMERID NOT NULL bLOCK

        if ( "UpdateChangeOrder".equals ( action ) )
        {
            //To check whether this sales order is already submitted...
            if ( !isTokenValid ( request ) )
            {
                errors.put ( ERROR_SALES_ORDER_ALREADY_SAVED, null );
            }

            resetToken ( request );
            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                saveToken ( request );
                return ( mapping.findForward ( "success" ) );
            }
            /*  Chekcing if the user has selected a new shipping address and if so then setting the shippingAddressID as the newShippingAddressID   */
            if ( subform.getShippingAddressId () == -1 && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
            }
            if ( customerId != null )
            {
                session.setAttribute ( "addShippingMethodCustomerId", customerId );
            }
            else
            {
                customerId = ( String ) session.getAttribute ( "addShippingMethodCustomerId" );
            }

                addNewSalesTaxState( request,session,errors,subform );
                //For setting the shipping method
                subform.setShippingMethod( subform.getShippingAccount() );
                request.setAttribute("salesOrderForm",subform);
                //Set the lineitems in the request,false is not to check for marketing limits
                ArrayList<LineItem> lineItems = loadLineItems(request,subform.getCustomerId(),errors,info,false, isSample);
                session.setAttribute("presentLineItems",lineItems);
                //Prabhanjan on 06 mar 2004
                session.setAttribute("lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals(lineItems));
                session.setAttribute("maxLineItemNo",request.getAttribute("maxLineItemNo"));

                //Load the reason codes in request
                request.setAttribute("marketingReasonCodes",SalesDAO.loadMarketingReasonCodes());
                request.setAttribute("salesReasonCodes",SalesDAO.loadSalesReasonCodes());
                request.setAttribute("financeReasonCodes",SalesDAO.loadFinanceReasonCodes());
                request.setAttribute("opsReasonCodes",SalesDAO.loadOpsReasonCodes());

                request.setAttribute("Account",subform.getShippingAccount());
                request.setAttribute("Method",subform.getShippingAccount());

                 subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
                 subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
                 subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());
                 salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
                 errors = ( HashMap<String, String> ) request.getAttribute("Errors");
                 if( !errors.isEmpty() )
                 {
                      request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
                 }
                 saveToken(request);
                 return (mapping.findForward("changeOrder"));
        }
        else if ( "SubmitChangeOrder".equals ( action ) ) // Begin SubmitChangeOrder
        {
            // Chekcing if the user has selected a new shipping address and if so then setting the shippingAddressID as the newShippingAddressID
            if ( subform.getShippingAddressId () == -1 && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
                session.removeAttribute ( "newShippingAddressId" );
            }

            if ( customerId != null )
            {
                session.setAttribute ( "addShippingMethodCustomerId", customerId );
            }
            else
            {
                customerId = ( String ) session.getAttribute ( "addShippingMethodCustomerId" );
            }
            addNewShippingMethod ( request, session, errors, info, subform, salesOrderFromMap );
            addNewSalesTaxState ( request, session, errors, subform );
            addNewShippingTerms ( request, session, errors, info, subform );
            SalesOrderAction.addNewDeliveryTerms ( request, session, errors, info, subform );
            SalesOrderAction.addNewShippingInstructions ( request, session, errors, info, subform );
            SalesOrderAction.addNewFreightInstructions ( request, session, errors, info, subform );

            //Set the form values and lineitems values, to show in the confirmation page
            session.setAttribute ( "salesOrderForm", subform );

            //Load the reason codes in request
            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );

            request.setAttribute ( "Account", subform.getShippingAccount () );
            //Method is also set to Account value as both account and method name now contains same concatenated value of method and account.
            request.setAttribute ( "Method", subform.getShippingAccount () );

            //Set the lineitems values , true for check for marketing limits
            ArrayList<LineItem> lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info, true, isSample );
            session.setAttribute ( "presentLineItems", lineItems );
            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );

            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

            subform.setTotalQty ( Integer.parseInt ( ( String ) request.getAttribute ( "totalQty" ) ) );

			subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
			subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
			subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            session.setAttribute ( "totalQty", request.getAttribute ( "totalQty" ) );
            session.setAttribute ( "salesTax", request.getAttribute ( "salesTax" ) );
            session.setAttribute ( "subTotal", request.getAttribute ( "subTotal" ) );

            session.setAttribute ( "orderTotal", Double.toString ( subform.getSalesTaxAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSubTotalAsDouble () ) );
            session.setAttribute ( "tempShippingMethod", subform.getShippingMethod() );
            subform.setOdm(CustomerDAO.getCustomerName( null, subform.getOdmId()) );
            subform.setEndCustomer( CustomerDAO.getCustomerName( null,subform.getEndCustomerId() ));
            String salesOrderNos = null;
            SalesOrder oldSalesOrder = null;
            if ( subform.getCustomerPO() != null && subform.getCustomerPO().trim().length() > 0 )
            {
                HashMap<String, SalesOrder> oldSalesOrderMap = ( HashMap<String, SalesOrder> ) session.getAttribute ( "oldSalesOrderMap" );
                if( oldSalesOrderMap != null )
                {
                    oldSalesOrder =  ( SalesOrder )oldSalesOrderMap.get( subform.getSalesOrderId()+"" );
                }
                if ( oldSalesOrder.getCustomerPO().trim().equalsIgnoreCase( subform.getCustomerPO().trim() ) == false )
                {
                    salesOrderNos = NewSalesOrderDAO.getSalesOrderNoForCustomerPO( null, subform.getCustomerPO().trim(), subform.getCustomerId(), subform.getSalesOrderNo() );
                }
            }
            if ( salesOrderNos != null && salesOrderNos.trim().length() > 0 )
            {
                if ( salesOrderNos.indexOf(",") > 0 )
                {
                    info.put( "Warning : Sales Orders ( "+salesOrderNos+" ) are already exists for this PO", null );
                } else
                {
                    info.put( "Warning : Sales Order ( "+salesOrderNos+" ) is already exists for this PO", null );
                }
            }
            request.setAttribute ( "salesOrderForm", subform );
            errors = ( HashMap<String, String> ) request.getAttribute ( "Errors" );
            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                return ( mapping.findForward ( "changeOrder" ) );
            }
            info = ( HashMap<String, String> ) request.getAttribute ( "Info" );

            if ( !info.isEmpty () )
            {
                request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
            }
            saveToken ( request );
            return ( mapping.findForward ( "confirmOrder" ) );
        } // End of SubmitChangeOrder
        else if ( "splitLineItems".equals ( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
            }

            ArrayList<LineItem> lineitems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );
            session.setAttribute ( "lineItemsFromChangeOrder", lineitems );
            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineitems ) );

            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );

            subform.setTotalQty(Integer.parseInt((String)request.getAttribute("totalQty")));
	        subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
			subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
			subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            session.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            session.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            session.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            session.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );
            session.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );
            return new ActionForward("/splitSalesOrder.do?salesOrderId="+subform.getSalesOrderId()+"&customerId="+subform.getCustomerId(), false);
        }
        else if ( "printView".equals ( action ) )
        {
            ApproverOrderForm approverOrderForm = new ApproverOrderForm ();
            SalesOrder salesOrder = new SalesOrder ();
            SalesOrderForm salesOrderForm = ( SalesOrderForm ) session.getAttribute ( "salesOrderForm" );
            PropertyUtils.copyProperties ( salesOrder, salesOrderForm );
            SalesOrderDAO.loadClientAddress ( salesOrder );

            //salesOrder.setShippingAddressAsObject ( CustomerDAO.getAddress ( salesOrder.getShippingAddressId() ) ); //commented by sujan on 17th dec 2004
            salesOrder.setShippingAddressAsObject( CustomerDAO.getAddressWithContactPersonDetails( salesOrder.getShippingAddressId(), salesOrder.getShippingContactPerson()) ); //added by sujan on 17th dec 2004
            salesOrder.setBillingAddressAsObject( CustomerDAO.getAddressWithContactPersonDetails( salesOrder.getBillingAddressId(), salesOrder.getBillingContactPerson(), salesOrder.getCustomerId() ) ); // modified by sujan on 16th dec 2004  'added the new parameter customerId'
            salesOrder.setShippingAccount( (String) session.getAttribute ( "tempShippingMethod" ) );

			// Modified by Prabhanjan (2 Apr 2004)
            salesOrder.setTotalQty((String)session.getAttribute("totalQty"));
            salesOrder.setFinalSubTotal(Double.parseDouble((String)session.getAttribute("subTotal")));
            salesOrder.setFinalSalesTax(Double.parseDouble((String)session.getAttribute("salesTax")));
            salesOrder.setFinalOrderTotal(Double.parseDouble((String) session.getAttribute("orderTotal")));

            approverOrderForm.setSalesOrderId ( salesOrderForm.getSalesOrderId () );
            approverOrderForm.setSalesOrderNo ( salesOrderForm.getSalesOrderNo () );

            String clientaddressId =  UserDAO.getClientAddressId();
            String addressId = null;
            String clientname = null;

            int finalAddressId = 0;
            if(clientaddressId != null)
            {
                StringTokenizer st = new StringTokenizer(clientaddressId,"@");
                try
                {
                    addressId = st.nextToken();
                    clientname = st.nextToken();
                }catch(NoSuchElementException e)
                {
                     clientname  = "";
                }
            }
            if(addressId  != null)
            {
                finalAddressId = Integer.parseInt(addressId);
            }
            Address clientAddress= UserDAO.loadClientAddressDetails( null , finalAddressId );

            salesOrder.setClientAddressAsObject(clientAddress);
            String clientAddress1 = SalesOrder.getClientAddressAsString(clientAddress);
            salesOrder.setClientAddress(clientAddress1);
            salesOrder.setClientName(clientname);
            salesOrder.setChangeNumber(salesOrderForm.getChangeNo());
            approverOrderForm.setSalesOrder ( salesOrder );

            // Added by Veeru on 23rd Nov 2004
            Customer customer = new Customer();
            customer.setCustomerId( salesOrder.getCustomerId() );
            CustomerDAO.getCustomerDetailsForAcknowledgement( null, customer );
            request.setAttribute ( "customer", customer );

            request.setAttribute ( "approverOrderForm", approverOrderForm );
            request.setAttribute ( "lineItems", session.getAttribute ( "presentLineItems" ) );

            ArrayList<LineItem> list = (ArrayList<LineItem>) request.getAttribute("lineItems");
            if ( list != null )
            {
                Collections.sort (list , new PackingSlipComparator () );
            }
            request.setAttribute ( "termsAndConditions", SalesDAO.loadTermsAndConditionsAsList () );

            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals( list ) );
            return ( mapping.findForward ( "printView" ) );
        }
        else if ( "EditChangeOrder".equals ( action ) )
        {
            if ( !isTokenValid ( request ) )
            {
                errors.put ( ERROR_SALES_ORDER_ALREADY_SAVED, null );
            }

            resetToken ( request );
            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                saveToken ( request );
                return ( mapping.findForward ( "successChange" ) );
            }
            request.setAttribute ( "salesOrderForm", session.getAttribute ( "salesOrderForm" ) );

            String hdnshippingAccount = request.getParameter ( "hdnshippingAccount" );
            request.setAttribute ( "Account", hdnshippingAccount );
            request.setAttribute ( "Method", hdnshippingAccount );
            if( "1".equals( request.getParameter("isSplit") ) )
            {
                subform = ( SalesOrderForm ) session.getAttribute ( "salesOrderForm" );
                ArrayList<LineItem> lineItems = (ArrayList<LineItem>)session.getAttribute ( "lineItems");

                session.setAttribute ( "presentLineItems", lineItems );
                session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
                request.setAttribute ( "Account", session.getAttribute("Account") );
                request.setAttribute ( "Method", session.getAttribute("Method") );
            }
            else
            {
                session.setAttribute ( "presentLineItems", ( ArrayList<LineItem> ) session.getAttribute ( "presentLineItems" ) );
            }
            salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
            session.setAttribute ( "maxLineItemNo", session.getAttribute ( "maxLineItemNo" ) );
            //Load the reason codes in request
            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );
            saveToken ( request );
            return ( mapping.findForward ( "changeOrder" ) );
        }
        else if ( "loadEndUserDetails".equals ( action ) )
        {
            String endUserId = request.getParameter ( "endUserId" );
            int salesOrderId = Integer.parseInt(request.getParameter ( "salesOrderId" ));
            if ( endUserId != null )
            {
                if ( "".equals ( endUserId.trim () ) )
                {
                    SalesOrder salesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );
                    subform.setContactPersons ( salesOrder.getContactPersons () );
                    subform.setBillingAddress ( SalesOrder.getAddressAsString ( salesOrder.getBillingAddressAsObject () ) );
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( salesOrder.getShippingAddressAsObject () ) );
                    subform.setContactPersonsForBillingAddress ( salesOrder.getContactPersonsForBillingAddress () );
                    subform.setContactPersonsForShippingAddress ( salesOrder.getContactPersonsForShippingAddress () );

                    HashMap billingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getBillingAddressId() , salesOrder.getBillingAddressAsObject ());
                    Address salesOrderAddress = CustomerDAO.getSalesOrderAddress ( salesOrderId );
                    Address address = CustomerDAO.getAddress ( salesOrder.getBillingAddressId () );
                    if( salesOrderAddress != null )
                    {
                        address.setPhoneNumber(salesOrderAddress.getPhoneNumber());
                        address.setCellNumber("");
                        address.setFaxNumber(salesOrderAddress.getFaxNumber());
                        address.setEmail(salesOrderAddress.getEmail());
                    }
                    address.setContactPerson(subform.getCustomerName());
                    address.setCellNumber("");
                    billingAddressMap.put("",SalesOrder.getAddressAsString(address));

                    session.setAttribute ( "billingAddressMap", billingAddressMap  );
                    HashMap<String, String> shippingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getShippingAddressId() , salesOrder.getShippingAddressAsObject ());
                    Address shipAddress = CustomerDAO.getAddress ( salesOrder.getShippingAddressId () );
                    shipAddress.setContactPerson("");
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                    shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    session.setAttribute ( "shippingAddressMap", shippingAddressMap );
                    subform.setBillingContactPerson(salesOrder.getBillingContactPerson());
                    subform.setShippingContactPerson(salesOrder.getShippingContactPerson());

                    subform.setShippingAddresses ( salesOrder.getShippingAddresses () );
                    subform.setEndUser ( "" );
                    subform.setBillingAddressId ( salesOrder.getBillingAddressId () );
                    subform.setShippingAddressId ( salesOrder.getShippingAddressId () );

                    session.setAttribute ( "mfgPartsWithCustomerPartNos", NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
                    session.setAttribute ( "mfgPartsWithLabelNumbers", NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
                }
                else
                {
                    EndUser endUser = EndUserDAO.getEndUserDetails ( Integer.parseInt ( endUserId ) );
                    subform.setContactPersonsForBillingAddress(CustomerDAO.getAllContactPersonsForAddress( endUser.getDefaultBillingAddressId() ));// Added by veeru on 29th April 2004
                    subform.setContactPersonsForShippingAddress(CustomerDAO.getAllContactPersonsForAddress( endUser.getDefaultShippingAddressId() ));// Added by veeru on 29th April 2004
                    ArrayList shippingAddresses = endUser.getShippingLocations ();
                    shippingAddresses.add ( 0, endUser.getShippingAddress () );

                    subform.setEndUser ( endUser.getEndUserName () );
                    subform.setOdmId( -1 );// Added by Veeru on 29th Nov 2004
                    subform.setOdm ( "" );
                    subform.setBillingAddressId ( endUser.getDefaultBillingAddressId () );
                    subform.setShippingAddressId ( endUser.getDefaultShippingAddressId () );
                    subform.setBillingAddress ( SalesOrder.getAddressAsString ( endUser.getBillingAddress () ) );
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( endUser.getShippingAddress () ) );
                    SalesOrder salesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );

                    subform.setBillingContactPerson(endUser.getBillingContactPersonObject().getContactPerson());
                    subform.setShippingContactPerson(endUser.getShippingContactPersonObject().getContactPerson());

                    HashMap<String, String> billingAddressMap = CustomerDAO.getAddressDetailsMap (  subform.getBillingAddressId() , endUser.getBillingAddress ());

                    Address salesOrderAddress = CustomerDAO.getSalesOrderAddress ( salesOrderId );
                    Address customerAddressObject = CustomerDAO.getAddress ( salesOrder.getBillingAddressId () );
                    Address billAddress = CustomerDAO.getAddress ( endUser.getDefaultBillingAddressId () );

                    String billContactPersonName = "";
                    if( billAddress != null )
                    {
                        billContactPersonName = billAddress.getContactPerson();

                        if( salesOrderAddress != null )
                        {
                            billAddress.setPhoneNumber( salesOrderAddress.getPhoneNumber() );
                            billAddress.setFaxNumber( salesOrderAddress.getFaxNumber() );
                            billAddress.setEmail( salesOrderAddress.getEmail() );
                        }
                        else
                        {
                            billAddress.setPhoneNumber( customerAddressObject.getPhoneNumber() );
                            billAddress.setFaxNumber( customerAddressObject.getFaxNumber() );
                            billAddress.setEmail( customerAddressObject.getEmail() );
                        }

                        billAddress.setContactPerson( subform.getCustomerName() );
                        billAddress.setCellNumber( "" );
                        billingAddressMap.put( "", SalesOrder.getAddressAsString( billAddress ) );

                        if( billContactPersonName == null || billContactPersonName.trim().length() == 0 || billContactPersonName.equals( subform.getCustomerName() ) )
                        {
                            subform.setBillingAddress( SalesOrder.getAddressAsString( billAddress ) );
                        }
                    }
                    session.setAttribute( "billingAddressMap", billingAddressMap );

                    HashMap<String, String> shippingAddressMap = CustomerDAO.getAddressDetailsMap ( subform.getShippingAddressId() , endUser.getShippingAddress ());
                    Address shipAddress = CustomerDAO.getAddress(endUser.getDefaultShippingAddressId());
                    if(shipAddress != null )
                    {
                        shipAddress.setContactPerson("");
                        shipAddress.setPhoneNumber("");
                        shipAddress.setCellNumber("");
                        shipAddress.setFaxNumber("");
                        shipAddress.setEmail("");
                        shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    }
                    session.setAttribute ( "shippingAddressMap", shippingAddressMap  );
                    subform.setContactPersons ( salesOrder.getContactPersons () );

                    Address address = endUser.getBillingAddress();
                    String billAddressWithoutContactPerson = getAddressAsString(address);
                    address = endUser.getShippingAddress();
                    String shipAddressWithoutContactPerson = getAddressAsString(address);
                    if ( billAddressWithoutContactPerson.trim ().equals ( "" ) )
                    {
                        subform.setBillingAddressId ( salesOrder.getBillingAddressId () );
                        Address billingAddress = salesOrder.getBillingAddressAsObject ();
                        subform.setBillingAddress ( SalesOrder.getAddressAsString ( billingAddress ) );
                        subform.setContactPersonsForBillingAddress ( salesOrder.getContactPersonsForBillingAddress () ); //Added by veeru on 29th April 2004
                        billingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getBillingAddressId() , salesOrder.getBillingAddressAsObject () );//Added by Veeru  on 26th April 2004
                        billingAddress = CustomerDAO.getAddress ( salesOrder.getBillingAddressId () );
                        if( salesOrderAddress != null )
                        {
                            billingAddress.setPhoneNumber(salesOrderAddress.getPhoneNumber());
                            billingAddress.setFaxNumber(salesOrderAddress.getFaxNumber());
                            billingAddress.setEmail(salesOrderAddress.getEmail());
                        }
                        billingAddress.setContactPerson(subform.getCustomerName());
                        billingAddress.setCellNumber("");
                        billingAddressMap.put("",SalesOrder.getAddressAsString(billingAddress));
                        session.setAttribute ( "billingAddressMap", billingAddressMap  );
                        subform.setBillingContactPerson ( salesOrder.getBillingContactPerson () );
                    }
                    if(shipAddressWithoutContactPerson.trim().equals(""))
                    {
                        subform.setShippingAddressId ( salesOrder.getShippingAddressId () );
                        Address shippingAddress = salesOrder.getShippingAddressAsObject();
                        subform.setShippingAddress ( SalesOrder.getAddressAsString ( shippingAddress ) );
                        subform.setShippingAddressId ( salesOrder.getShippingAddressId() );
                        //shippingAddresses.add( shippingAddress );
                        subform.setContactPersonsForShippingAddress ( salesOrder.getContactPersonsForShippingAddress () ); //Added by veeru on 25th April 2004
                        subform.setShippingContactPerson ( salesOrder.getShippingContactPerson () );
                        shippingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getShippingAddressId() , salesOrder.getShippingAddressAsObject ());
                        shipAddress = CustomerDAO.getAddress ( salesOrder.getShippingAddressId () );
                        shipAddress.setContactPerson("");
                        shipAddress.setPhoneNumber("");
                        shipAddress.setCellNumber("");
                        shipAddress.setFaxNumber("");
                        shipAddress.setEmail("");
                        shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                        session.setAttribute ( "shippingAddressMap", shippingAddressMap );
                    }
                    //To get the customer default shipping address when the end user is selected for the quotation.
                    shippingAddresses.add ( CustomerDAO.getAddress ( SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId() ) ) );
                    subform.setShippingAddresses ( loadShippingAddresses ( shippingAddresses ) );
                    session.setAttribute ( "mfgPartsWithCustomerPartNos", EndUserDAO.loadManfacturingPartNumbersWithEndUserPartNos ( Integer.parseInt ( endUserId ) ) );
                    session.setAttribute ( "mfgPartsWithLabelNumbers",EndUserDAO.loadManfacturingPartNumbersWithEndUserLabelNumbers ( Integer.parseInt ( subform.getEndUserId () ) ) );
                }
                subform.setIsEndCustomerShipAddress( false );
            }

            session.setAttribute ( "contactPersons", subform.getContactPersons () );
            session.setAttribute ( "billingAddressContactPersons", subform.getContactPersonsForBillingAddress() );
            session.setAttribute ( "shippingAddressContactPersons", subform.getContactPersonsForShippingAddress() );
            session.setAttribute ( "shippingAddresses", subform.getShippingAddresses () );
            session.setAttribute ( "salesPersons",CustomerDAO.loadAllSalesPersonsforCustomer(subform.getCustomerId () ) ) ;
            session.setAttribute ( "mfgParts", SalesOrderDAO.loadAllManfacturingPartNosOfCustomerWithOutobsolete ( subform.getCustomerId (), isSample ) );
            session.setAttribute ( "mfgPartsWithComments", SalesOrderDAO.loadAllManfacturingPartNumbersWithComments ( subform.getCustomerId (), isSample ) );
            session.setAttribute ( "mktgParts", SalesOrderDAO.loadAllMarketingPartNumbers () );
            session.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );
            ArrayList<LineItem> lineitems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );
            ArrayList<LineItem> previousLineItems = salesOrderFromMap.getPreviousLineItems() ;

            /*if ( "".equals ( endUserId ) )
            {
                SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, lineitems, subform.getCustomerId (), subform.getOdmId() );
                SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, previousLineItems, subform.getCustomerId (),subform.getOdmId() );
            }
            else
            {
                SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, lineitems, Integer.parseInt ( endUserId ) );
                SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, previousLineItems, Integer.parseInt ( endUserId ) );
            }*/
            request.setAttribute ( "presentLineItems", lineitems );
            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineitems ) );
            session.setAttribute ( "previousLineItems", previousLineItems );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            session.setAttribute ( "shippingMethods", CustomerDAO.loadSalesOrderShippingMethods( subform.getCustomerId() ) );
            subform.setTotalQty(Integer.parseInt((String)request.getAttribute("totalQty")));
            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );

            request.setAttribute ( "salesOrderForm", subform );

            saveToken ( request );
            return ( mapping.findForward ( "changeOrder" ) );
        }
        else if ( "loadODMDetails".equals ( action ) )
        {
            String odmId = request.getParameter ( "odmId" );
            if ( odmId != null )
            {
                if ( "-1".equals ( odmId.trim () ) )
                {
                    SalesOrder salesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );
                    subform.setContactPersons ( salesOrder.getContactPersons () );
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( salesOrder.getShippingAddressAsObject () ) );
                    subform.setContactPersonsForBillingAddress ( salesOrder.getContactPersonsForBillingAddress () );
                    subform.setContactPersonsForShippingAddress ( salesOrder.getContactPersonsForShippingAddress () );
                    HashMap<String, String> shippingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getShippingAddressId() , salesOrder.getShippingAddressAsObject ());
                    Address shipAddress = CustomerDAO.getAddress ( salesOrder.getShippingAddressId () );
                    shipAddress.setContactPerson("");
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                    shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    salesOrderFromMap.setShippingAddressMap( shippingAddressMap );
                    subform.setShippingContactPerson(salesOrder.getShippingContactPerson());
                    subform.setShippingAddresses ( salesOrder.getShippingAddresses () );
                    subform.setShippingAddressId ( salesOrder.getShippingAddressId () );
                    salesOrderFromMap.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
                    salesOrderFromMap.setMfgPartsWithLabelNumbers( NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
                    salesOrderFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer(subform.getCustomerId () ) ) ;
                    salesOrderFromMap.setShippingMethods( CustomerDAO.loadSalesOrderShippingMethods( subform.getCustomerId() ));
                }
                else
                {
                    SalesOrder salesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );
                    SalesOrder odmSalesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( odmId );
                    Address customerShippingAddress = salesOrder.getShippingAddressAsObject();
                    subform.setContactPersonsForBillingAddress( salesOrder.getContactPersonsForBillingAddress () );
                    subform.setContactPersonsForShippingAddress( odmSalesOrder.getContactPersonsForShippingAddress () );
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( odmSalesOrder.getShippingAddressAsObject () ) );
                    subform.setShippingContactPerson( odmSalesOrder.getShippingContactPerson () );
                    subform.setBillingAddressId ( salesOrder.getBillingAddressId () );
                    subform.setShippingAddressId ( odmSalesOrder.getShippingAddressId () );

                    ArrayList shippingAddresses = odmSalesOrder.getShippingAddresses();

                    subform.setContactPersons ( salesOrder.getContactPersons () );
                    HashMap<String, String> shippingAddressMap = CustomerDAO.getAddressDetailsMap ( odmSalesOrder.getShippingAddressId() , odmSalesOrder.getShippingAddressAsObject ());
                    Address shipAddress = CustomerDAO.getAddress(odmSalesOrder.getShippingAddressId());
                    shipAddress.setContactPerson("");
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                    shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    salesOrderFromMap.setShippingAddressMap( shippingAddressMap );
                    Address address = odmSalesOrder.getShippingAddressAsObject();
                    String shipAddressWithoutContactPerson = getAddressAsString(address);

                    if(shipAddressWithoutContactPerson.trim().equals(""))
                    {
                        subform.setShippingAddressId ( salesOrder.getShippingAddressId () );
                        subform.setShippingAddress ( SalesOrder.getAddressAsString ( customerShippingAddress ) );
                        subform.setContactPersonsForShippingAddress ( salesOrder.getContactPersonsForShippingAddress () );
                        subform.setShippingContactPerson(salesOrder.getShippingContactPerson());
                        shippingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getShippingAddressId() , salesOrder.getShippingAddressAsObject ());
                        shipAddress = CustomerDAO.getAddress ( salesOrder.getShippingAddressId () );
                        shipAddress.setContactPerson("");
                        shipAddress.setPhoneNumber("");
                        shipAddress.setCellNumber("");
                        shipAddress.setFaxNumber("");
                        shipAddress.setEmail("");
                        shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                        salesOrderFromMap.setShippingAddressMap( shippingAddressMap );
                    }
                    subform.setEndUser ( "" );
                    subform.setEndUserId ( "" );
                    ArrayList defaultShippingAddress = new ArrayList();
                    if ( customerShippingAddress != null )
                    {
                        defaultShippingAddress.add( customerShippingAddress );
                        ArrayList<LabelValueBean> farmatedDefualtShippingAddress = loadShippingAddresses ( defaultShippingAddress );
                        for ( int i = 0; i < farmatedDefualtShippingAddress.size(); i++ ) {
                            org.apache.struts.util.LabelValueBean bean = ( org.apache.struts.util.LabelValueBean ) farmatedDefualtShippingAddress.get( i );
                            shippingAddresses.add( bean );
                        }
                    }
                    subform.setShippingAddresses ( shippingAddresses );
                    salesOrderFromMap.setShippingAddresses( shippingAddresses );
                    salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
                }
                subform.setIsEndCustomerShipAddress( true );
            }
            salesOrderFromMap.setContactPersons( subform.getContactPersons () );
            salesOrderFromMap.setContactPersonsForBillingAddress( subform.getContactPersonsForBillingAddress() );
            salesOrderFromMap.setContactPersonsForShippingAddress( subform.getContactPersonsForShippingAddress() );
            salesOrderFromMap.setShippingAddresses( subform.getShippingAddresses () );
            ArrayList<LineItem> lineitems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );
            SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, lineitems, subform.getCustomerId (), subform.getOdmId() );
            //SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, previousLineItems, subform.getCustomerId (), subform.getOdmId() );
            //NewSalesOrderDAO.loadOdmLabelNumbersForLineItems ( null, lineitems, subform.getCustomerId (),Integer.parseInt ( odmId ) );
            //NewSalesOrderDAO.loadOdmLabelNumbersForLineItems ( null, previousLineItems, subform.getCustomerId (), Integer.parseInt ( odmId ) );
            request.setAttribute ( "presentLineItems", lineitems );
            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineitems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            subform.setTotalQty(Integer.parseInt((String)request.getAttribute("totalQty")));
            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );

            request.setAttribute ( "salesOrderForm", subform );

            saveToken ( request );
            return ( mapping.findForward ( "changeOrder" ) );
        }
        else if ("loadBillingAddress".equals(action))
        {
            if ((subform.getShippingAddressId() == -1) && (session.getAttribute("newShippingAddressId") != null)) {
                subform.setShippingAddressId(Integer.parseInt((String) session.getAttribute("newShippingAddressId")));
                Address address = CustomerDAO.getAddress(subform.getShippingAddressId());
                loadShippingAddress(address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap);
            }
            int billingAddressId = subform.getBillingAddressId();

            Address billingAddress = CustomerDAO.getAddressWithContactPersonDetails(billingAddressId);
            HashMap<String,String> billingAddressMap = new HashMap<String,String>();
            if (billingAddress != null) {
                subform.setBillingContactPerson(billingAddress.getContactPerson());
                subform.setBillingAddress(billingAddress.getAddressAsString());
                billingAddressMap = CustomerDAO.getAddressDetailsMap(billingAddressId, billingAddress);
                billingAddressMap.put("", billingAddress.getAddressWithoutContactPersonAsString());
            }
            salesOrderFromMap.setBillingAddressMap(billingAddressMap);
            salesOrderFromMap.setContactPersonsForBillingAddress(CustomerDAO.getAllContactPersonsForAddress(billingAddressId));
            salesOrderFromMap.setShippingMethods(CustomerDAO.loadShippingMethodsForCustomerAndOdm(subform.getCustomerId(), subform.getOdmId()));
            ArrayList<LineItem> lineitems = loadLineItems(request, subform.getCustomerId(), errors, info, false, isSample);
            request.setAttribute("presentLineItems", lineitems);
            session.setAttribute("lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals(lineitems));
            session.setAttribute("maxLineItemNo", request.getAttribute("maxLineItemNo"));
            request.setAttribute("Account", subform.getShippingAccount());
            request.setAttribute("Method", subform.getShippingAccount());
            subform.setTotalQty(Integer.parseInt((String) request.getAttribute("totalQty")));
            subform.setSalesTaxAsDouble(Double.parseDouble((String) request.getAttribute("salesTax")));
            subform.setSubTotalAsDouble(Double.parseDouble((String) request.getAttribute("subTotal")));
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble() + subform.getFrieghtAsDouble() + subform.getMiscAsDouble() + subform.getSalesTaxAsDouble());

            request.setAttribute("marketingReasonCodes", SalesDAO.loadMarketingReasonCodes());
            request.setAttribute("salesReasonCodes", SalesDAO.loadSalesReasonCodes());
            request.setAttribute("financeReasonCodes", SalesDAO.loadFinanceReasonCodes());
            request.setAttribute("opsReasonCodes", SalesDAO.loadOpsReasonCodes());
            request.setAttribute("salesOrderForm", subform);
            saveToken(request);
            return (mapping.findForward("changeOrder"));
        }
        else if ( "loadShippingAddress".equals ( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
            }
            int shippingAddressId = subform.getShippingAddressId();
            Address shipAddress = CustomerDAO.getAddressWithContactPersonDetails ( shippingAddressId );
            HashMap<String,String> shippingAddressMap = new HashMap<String,String>();
            if( shipAddress != null )
            {
                subform.setShippingContactPerson( shipAddress.getContactPerson() );
                subform.setShippingAddress ( shipAddress.getAddressAsString ( ));
                shippingAddressMap = CustomerDAO.getAddressDetailsMap ( shippingAddressId, shipAddress);
                shippingAddressMap.put("",shipAddress.getAddressWithoutContactPersonAsString());
            }
            salesOrderFromMap.setShippingAddressMap( shippingAddressMap );
            salesOrderFromMap.setContactPersonsForShippingAddress( CustomerDAO.getAllContactPersonsForAddress(  shippingAddressId ) );
            salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
            ArrayList<LineItem> lineitems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );
            request.setAttribute ( "presentLineItems", lineitems );
            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineitems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            subform.setTotalQty(Integer.parseInt((String)request.getAttribute("totalQty")));
            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );
            request.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );
            return ( mapping.findForward ( "changeOrder" ) );
        }
        else if ( "loadShippingInstructions".equals ( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
            }
            subform.setShippingInstructions ( NewSalesOrderDAO.loadSelectedShippingInstructions( null, subform.getShippingInstructionsId() ) );
            ArrayList<LineItem> lineitems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );
            request.setAttribute ( "presentLineItems", lineitems );
            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineitems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            subform.setTotalQty(Integer.parseInt((String)request.getAttribute("totalQty")));
            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());
            salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );
            request.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );
            return ( mapping.findForward ( "changeOrder" ) );
        }
        else if ( "loadEndCustomerDefualtShippingAddress".equals ( action ) )
        {
            ArrayList shippingList = new ArrayList();
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, shippingList, salesOrderFromMap );
            }
            salesOrderFromMap.setShippingAddresses(shippingList);
            int shippingAddressId = 0 ;
            if ( subform.getIsEndCustomerShipAddress() == false )
            {
                NewSalesOrderDAO.loadCustomerAddressesOfType(shippingList, subform.getCustomerId(), "Shipping");
                shippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId () );
            }
            else
            {
                if ( subform.getOdmId() > 0 )
                {
                    NewSalesOrderDAO.loadCustomerAddressesOfType(shippingList, subform.getOdmId(), "Shipping");
                    shippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getOdmId () );
                }
                else
                {
                    NewSalesOrderDAO.loadCustomerAddressesOfType(shippingList, subform.getCustomerId(), "Shipping");
                    shippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId () );
                }
            }
            String formContactPerson = null;
            if ( NewSalesOrderDAO.isAddressIdExists( shippingList, subform.getShippingAddressId() ) )
            {
                formContactPerson = subform.getShippingContactPerson();
                shippingAddressId = subform.getShippingAddressId();
            }
            else
            {
                subform.setShippingAddressId(shippingAddressId);
            }

            Address shipAddress = CustomerDAO.getAddress ( shippingAddressId );
            HashMap<String, String> shippingAddressMap = new HashMap<String, String>();
            if( shipAddress != null )
            {
                /*String shipAddressWithoutContactPerson = getAddressAsString( shipAddress );
                if ( "".equals( shipAddressWithoutContactPerson.trim() ) )
                {
                    int defaultShippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId () );
                    if ( defaultShippingAddressId != shippingAddressId )
                    {
                        shippingAddressId = defaultShippingAddressId;
                        subform.setShippingAddressId( shippingAddressId);
                        shipAddress = CustomerDAO.getAddress ( shippingAddressId );
                        subform.setShippingContactPerson( shipAddress.getContactPerson() );
                        formContactPerson = null;
                    }
                }*/
                if ( formContactPerson != null )
                {
                    subform.setShippingContactPerson( formContactPerson );
                }
                else
                {
                    subform.setShippingContactPerson( shipAddress.getContactPerson() );
                }
                ContactPerson shippingContactPerson = CustomerDAO.getAddressContactPersonDetails (shippingAddressId , subform.getShippingContactPerson());
                if( shippingContactPerson != null )
                {
                    shipAddress.setContactPerson(shippingContactPerson.getContactPerson());
                    shipAddress.setPhoneNumber(shippingContactPerson.getPhoneNumber());
                    shipAddress.setCellNumber(shippingContactPerson.getCellNumber());
                    shipAddress.setFaxNumber(shippingContactPerson.getFaxNumber());
                    shipAddress.setEmail(shippingContactPerson.getEmail());
                }
                else
                {
                    shipAddress.setContactPerson( "" );
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                }
                subform.setShippingAddress ( shipAddress.getAddressAsString ( ));
                shippingAddressMap = CustomerDAO.getAddressDetailsMap ( shippingAddressId, shipAddress);
                shippingAddressMap.put("",shipAddress.getAddressWithoutContactPersonAsString());
            }
            salesOrderFromMap.setShippingAddressMap( shippingAddressMap );
            salesOrderFromMap.setContactPersonsForShippingAddress( CustomerDAO.getAllContactPersonsForAddress(  shippingAddressId ) );
            ArrayList<LineItem> lineitems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );

            request.setAttribute ( "presentLineItems", lineitems );

            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineitems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            subform.setTotalQty(Integer.parseInt((String)request.getAttribute("totalQty")));
            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());
            salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
            salesOrderFromMap.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );
            request.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );
            return ( mapping.findForward ( "changeOrder" ) );
        }   // End of loadEndCustomerDefualtShippingAddress
        else if ( "ConfirmChangeOrder".equals ( action ) ) // Begin Confirm
        {
            if ( !isTokenValid ( request ) )
            {
                errors.put ( ERROR_SALES_ORDER_ALREADY_SAVED, "" );
            }
            resetToken ( request );

            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                saveToken ( request );
                return ( mapping.findForward ( "successChange" ) );
            }
            String emptyStr = new String("\"empty\"");
            SalesOrder salesOrder = new SalesOrder ();
            boolean isSampleBoolean = false;

            if( isSample == 0 )
            {
                isSampleBoolean = true;
            }

            PropertyUtils.copyProperties ( salesOrder, ( SalesOrderForm ) session.getAttribute ( "salesOrderForm" ) );
            if ( salesOrder.getShippingAddressId () == 0 )
            {
                salesOrder.setShippingAddressId ( SalesOrderDAO.getDefaultShippingAddressId ( salesOrder.getCustomerId () ) );
            }
            String account = "";

            String temp = salesOrder.getShippingAccount ();
            account = temp;
            if ( temp != null )
            {
                int index1 = temp.indexOf ( "#" );

                if ( index1 != -1 && index1 != 0 )
                {
                    account = temp.substring ( index1 + 1, temp.length () ).trim ();
                }
            }
            salesOrder.setShippingMethod ( salesOrder.getShippingMethod ().trim () );
            salesOrder.setShippingAccount ( account );



            DBTransaction dbTransaction = null;
            boolean success = false;
            Alarm alarm = null;
            int salesOrderId = -1;
            int updateStatus = 0;
            String no = null;
            //For storing the changes summary to be sent inthe mail notifications
            String changesSummary = "";
            SalesOrder oldSalesOrder = null;
            ArrayList<LineItem> presentLineItemsList = ( ArrayList<LineItem> ) session.getAttribute ( "presentLineItems" );
            String status               = null;
            String holdsAuditTrail      = "";
            String salesOrderStatus     = null;

            try
            {
                //Begine Transaction
                dbTransaction = DBTransaction.getInstance ();
                dbTransaction.begin ();
                //Save the salesOrder details & get the salesOrderId
                salesOrder.setEnteredById ( user.getUserId () );
                salesOrder.setEnteredByName ( user.getFirstName () + " " + user.getLastName () );
                updateStatus = SalesOrderDAO.saveChangeSalesOrder ( dbTransaction, salesOrder );
                salesOrderId = salesOrder.getSalesOrderId ();
                no = request.getParameter ( "changeNo" );
                String reason = salesOrder.getReason ();
                HashMap oldSalesOrderMap = ( HashMap ) session.getAttribute ( "oldSalesOrderMap" );
                if( oldSalesOrderMap != null ){
                    oldSalesOrder =  ( SalesOrder )oldSalesOrderMap.get( salesOrder.getSalesOrderId()+"" );
                }
                String salesOrderChanges = SalesOrderDAO.checkSalesOrderChanges ( dbTransaction, oldSalesOrder, salesOrder, no );
                String finalComments = null;
                if ( !oldSalesOrder.getComments ().equals ( salesOrder.getComments () ) )
                {
                    finalComments = "###<br> Comments is changed from <b><I> " + ("".equals(oldSalesOrder.getComments().trim())? emptyStr : oldSalesOrder.getComments()) + "</I></b>  to <b><I> " + ("".equals(salesOrder.getComments().trim()) ? "-" : salesOrder.getComments() ) + "</I></b>  ";
                }
                if ( finalComments == null )
                {
                    finalComments = "###";
                }
                String changes = SalesOrderDAO.checkForAllLineItemChanges ( dbTransaction, salesOrderId, ( ArrayList ) session.getAttribute ( "presentLineItems" ), no );
                /*Checks whether existing LineItem Details are modified or not, if modified Set lineItemDetailsModified to True AND also returns summary*/
                changesSummary = SalesOrderDAO.getNotificationChangeSummary ( dbTransaction, salesOrderId, ( ArrayList ) session.getAttribute ( "presentLineItems" ) );

                SalesOrderDAO.saveChangeLineItems ( dbTransaction, salesOrderId, presentLineItemsList, reason, user.getUserId (), updateStatus, isSampleBoolean  );

                holdsAuditTrail = SalesOrderDAO.setCustomerHolds( dbTransaction, user, presentLineItemsList, salesOrder.getCustomerId(), salesOrderId, isSampleBoolean );

                status = SalesDAO.loadOrderStatus ( dbTransaction, salesOrderId );
                changes = changes + holdsAuditTrail;

                alarm = SalesOrderDAO.updateAlarmForChangeOrder ( dbTransaction, reason, salesOrderId, user );

                boolean flag = false;
                if ( ( salesOrderChanges != null && salesOrderChanges.length () != 0 && changes != null && changes.length () != 0 && flag == false ) || finalComments != null )
                {
                    SalesDAO.updateSalesAuditTrail ( dbTransaction, salesOrderId, user.getUserId (), changes, "" );
                    SalesDAO.updateSalesAuditTrail ( dbTransaction, salesOrderId, user.getUserId (), salesOrderChanges, finalComments );
                    flag = true;
                }
                else if ( ( salesOrderChanges != null && salesOrderChanges.length () != 0 && flag == false ) )
                {
                    SalesDAO.updateSalesAuditTrail ( dbTransaction, salesOrderId, user.getUserId (), salesOrderChanges, finalComments );
                }
                else if ( changes != null && changes.length () != 0 && flag == false )
                {
                    SalesDAO.updateSalesAuditTrail ( dbTransaction, salesOrderId, user.getUserId (), changes, finalComments );
                }
                success = true;

                request.setAttribute ( "salesOrderId", Integer.toString ( salesOrderId ) );
            }
            catch ( ScalarException se )
            {
                errors.put ( ERROR_IN_SAVING_CHANGE_ORDER_DETAILS, null );
                errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could not store Change Order Details " );
                session.setAttribute ( SessionKeys.ERROR_REPORT, se );
            }
            finally
            {
                // Rollback or Commit the Transaction
                if ( success == true )
                {
                    dbTransaction.commit ();
                    if( status.trim().length()==0)
                    {
                        if ( isSample == 1 )
                        {
                            errors.put ( "SalesOrder = " + salesOrder.getSalesOrderNo (), "Saved and Approved Successfully" );
                            errors.put ( "View/Print ", "Click here to <a href='javascript:openSalesOrder();' onmouseover=\"window.status='Click here to View/print Changed Sales Order';return true\" onmouseout=\"window.status='';return true\" > view/print </a>Sales Order Details" );
                        }
                        else
                        {
                            errors.put ( "SampleOrder = " + salesOrder.getSalesOrderNo (), "Saved and Approved Successfully" );
                            errors.put ( "View/Print ", "Click here to <a href='javascript:openSalesOrder();' onmouseover=\"window.status='Click here to View/print Changed Sample Order';return true\" onmouseout=\"window.status='';return true\" > view/print </a>Sample Order Details" );
                        }
                    }
                    else
                    {
                        if ( isSample == 1 )
                        {
                            errors.put ( "SalesOrder = " + salesOrder.getSalesOrderNo (), "Saved Successfully" );
                            errors.put ( "View/Print ", "Click here to <a href='javascript:openSalesOrder();' onmouseover=\"window.status='Click here to View/print Changed Sales Order';return true\" onmouseout=\"window.status='';return true\" > view/print </a>Sales Order Details" );
                        }
                        else
                        {
                            errors.put ( "SampleOrder = " + salesOrder.getSalesOrderNo (), "Saved Successfully" );
                            errors.put ( "View/Print ", "Click here to <a href='javascript:openSalesOrder();' onmouseover=\"window.status='Click here to View/print Changed Sample Order';return true\" onmouseout=\"window.status='';return true\" > view/print </a>Sample Order Details" );
                        }
                    }
                    try
                    {
                        String salesOrderChangeSummary = getSalesOrderChangeSummary ( null, SalesOrderDAO.loadSalesOrder ( String.valueOf ( salesOrderId ) ), oldSalesOrder  );
                        //alarm.setRecipients ( AlarmDAO.loadRecipientsWithBoardKitChipAccess ( Integer.parseInt ( ( String ) request.getAttribute ( "salesOrderId" ) ), alarm ) );
                        if ( salesOrder.getSalesPerson() != null && salesOrder.getSalesPerson().length() > 0 )
                        {
                            SalesPerson salesPerson = NewCustomerDAO.getSalesPersonDetails( null, salesOrder.getSalesPerson() );
                            if ( salesPerson != null && salesPerson.isSalesAckMail() )
                            {
                                if ( salesPerson.getAddress() != null && salesPerson.getAddress().getEmail() != null && salesPerson.getAddress().getEmail().trim().length() > 0 )
                                {
                                    alarm.addRecipient ( new AlarmUser( salesPerson.getSalesPerson (), salesPerson.getAddress().getEmail().trim() ) );
                                }
                            }
                        }
                        salesOrderStatus = SalesDAO.loadStatus( null, salesOrderId );
                        if( salesOrderStatus != null && salesOrderStatus.indexOf( Constants.SALESORDER_STATUS_HOLD ) >= 0  )
                        {
                            salesOrderStatus = Constants.SALESORDER_STATUS_HOLD;
                        }
                        if( isSample == 0 )
                        {
                            alarm.setSubject( "Sample Order Notification - SampleOrder No.: " + salesOrder.getSalesOrderNo() + " - Customer: " + salesOrder.getCustomerName() + " - Status: " + salesOrderStatus + " -- UPDATED");
                        }
                        else
                        {
                            alarm.setSubject( "Sales Order Notification - SO No.: " + salesOrder.getSalesOrderNo() + " - Customer: " + salesOrder.getCustomerName() + " - Status: " + salesOrderStatus + " -- UPDATED" );
                        }
                        
                        alarm.notifyAllRecipients ( SalesOrder.getHtmlViewWithChangeSummary ( salesOrderId, salesOrderChangeSummary + changesSummary ) );

                        if( status.trim ().length () == 0 )
                        {
                            SalesDAO.updateAlarmAndSendMailWithChangeSummary ( "", salesOrder.getSalesOrderId() , true, user, "" );
                        }
                        if( salesOrderChangeSummary != null && salesOrderChangeSummary.length() > 0 )
                        {
                        	SalesOrderHelper.notifyApprovedSalesOrderInfo ( salesOrder.getSalesOrderId() );	
                        }
                        errors.put ( "Email ", " has been sent to all approvers" );
                        //SalesOrderHelper.notifyFinanceReasonCode ( salesOrder.getSalesOrderId() );
                    }
                    catch ( Exception ex )
                    {
                        ex.printStackTrace();
                        errors.put ( "Email ", ERROR_IN_SENDING_MAILS_TO_APPROVERS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could not Send mails to Approvers " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, null );
                    }

                    try
                    {
                        InternalCommentsAction.notifiyInternalComments( "SalesOrder-" + salesOrder.getSalesOrderNo(), null, salesOrderId, alarm );
                    }
                    catch ( Exception e )
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not send Internal Comments notification" );
                    }
                }
                else
                {
                    if ( dbTransaction != null )
                    {
                        dbTransaction.rollback ();
                    }
                    if ( !salesOrder.getIsSample () )
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SALES_ORDER_DETAILS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could not Save Sales Order Details " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, null );
                    }
                    else
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SALES_ORDER_DETAILS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could not Save the Sample Order Details " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, null );
                    }
                }
            }

            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.MESSAGES, errors );
            }
            salesOrderMap.remove( salesOrder.getCustomerId()+"" );

            return ( mapping.findForward ( "successChange" ) );

        } // End of confirm
        else if ( "loadFreightInstructions".equals ( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, salesOrderFromMap.getShippingAddresses(), salesOrderFromMap );
            }
            String freightInstructions = null;
            try
            {
                freightInstructions = NewSalesOrderDAO.loadSelectedFreightInstructions( null, subform.getFreightInstructionsId() );
            }
            catch ( ScalarException e )
            {
                System.out.println ( "Exception While loading freight instructions" );
                e.printStackTrace();
            }
            subform.setFreightInstructions ( freightInstructions );

            ArrayList<LineItem> lineitems = loadLineItems ( request, subform.getCustomerId (), errors, info, false, isSample );
            request.setAttribute ( "presentLineItems", lineitems );
            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineitems ) );

            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );

            subform.setTotalQty(Integer.parseInt((String)request.getAttribute("totalQty")));
            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());
            salesOrderFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );
            request.setAttribute ( "salesOrderForm", subform );
            saveToken ( request );
            return ( mapping.findForward ( "changeOrder" ) );
        }
        else if ( request.getParameter ( "salesOrderId" ) != null )
        {
            SalesOrder salesOrder = null;
            String status = "";
            try
            {
                salesOrder = SalesOrderDAO.loadSalesOrder ( request.getParameter ( "salesOrderId" ) );
                if ( salesOrderMap == null )
                {
                    salesOrderMap = new HashMap<String, SalesOrder>();
                }
                salesOrderMap.put( salesOrder.getCustomerId()+"", salesOrder );
                session.setAttribute( "salesOrderMap", salesOrderMap );
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( ERROR_SALES_ORDER_INFORMATION_MISSING, null );
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                return mapping.findForward( "successChange" ); //returning to the search screen
            }

            HashMap<String, SalesOrder> oldSalesOrderMap = ( HashMap<String, SalesOrder> )session.getAttribute ( "oldSalesOrderMap" );
            if( oldSalesOrderMap == null )
            {
                oldSalesOrderMap = new HashMap<String, SalesOrder>();
            }
            oldSalesOrderMap.put( salesOrder.getSalesOrderId()+"", salesOrder );
            session.setAttribute ( "oldSalesOrderMap", oldSalesOrderMap );

            Address addressFromSalesOrder = salesOrder.getBillingAddressAsObject();
            SalesOrder customerSalesOrder = SalesOrderDAO.getSalesOrderCustomerDetails ( Integer.toString ( salesOrder.getCustomerId () ) );
            PropertyUtils.copyProperties ( subform, customerSalesOrder );
            subform.setChangeNo ( SalesOrderDAO.loadChangeNo ( salesOrder.getSalesOrderId () ) );
            Address customerAddressObject = null;
            customerAddressObject = CustomerDAO.getSalesOrderAddress ( salesOrder.getSalesOrderId() );
            if( customerAddressObject == null )
            {
                customerAddressObject = CustomerDAO.getAddress ( customerSalesOrder.getBillingAddressId () );
            }
            ContactPerson customerContactPerson = new ContactPerson();
            customerContactPerson.setContactPerson(subform.getCustomerName());
            customerContactPerson.setPhoneNumber(customerAddressObject.getPhoneNumber());
            customerContactPerson.setCellNumber("");
            customerContactPerson.setFaxNumber(customerAddressObject.getFaxNumber());
            customerContactPerson.setEmail(customerAddressObject.getEmail());
            HashMap<String, ContactPerson> customerContactPersonMap = CustomerDAO.getContactPersonDetailsMap ( salesOrder.getCustomerId());
            customerContactPersonMap.put(subform.getCustomerName(),customerContactPerson);
            salesOrder.setCustomerContactPersonMap( customerContactPersonMap );

            HashMap<String, String> billingAddressMap = CustomerDAO.getAddressDetailsMap ( salesOrder.getBillingAddressId() , salesOrder.getBillingAddressAsObject ());
            addressFromSalesOrder.setContactPerson("");
            addressFromSalesOrder.setPhoneNumber(customerAddressObject.getPhoneNumber());
            addressFromSalesOrder.setCellNumber("");
            addressFromSalesOrder.setFaxNumber(customerAddressObject.getFaxNumber());
            addressFromSalesOrder.setEmail(customerAddressObject.getEmail());
            billingAddressMap.put("",addressFromSalesOrder.getAddressAsString());
            salesOrder.setBillingAddressMap( billingAddressMap );

            HashMap<String, String> shippingAddressMap = new HashMap<String, String>();
            int shippingAddressId = salesOrder.getShippingAddressId ();
            Address shipAddress = CustomerDAO.getAddress ( shippingAddressId );

            shippingAddressMap = CustomerDAO.getAddressDetailsMap ( shippingAddressId , shipAddress );
            shippingAddressMap.put("",shipAddress.getAddressWithoutContactPersonAsString());
            salesOrder.setShippingAddressMap( shippingAddressMap );

            ArrayList shippingAddressesList = new ArrayList();
            if ( salesOrder.getIsEndCustomerShipAddress() )
            {
                if ( salesOrder.getOdmId() > 0 )
                {
                    NewSalesOrderDAO.loadCustomerAddressesOfType(shippingAddressesList, salesOrder.getOdmId(), Constants.ADDRESS_TYPE_SHIPPING);
                }
                else
                {
                    NewSalesOrderDAO.loadCustomerAddressesOfType(shippingAddressesList, salesOrder.getCustomerId(), Constants.ADDRESS_TYPE_SHIPPING);
                }
            }
            else
            {
                NewSalesOrderDAO.loadCustomerAddressesOfType(shippingAddressesList, salesOrder.getCustomerId(), Constants.ADDRESS_TYPE_SHIPPING);
            }
            salesOrder.setShippingAddresses ( shippingAddressesList );

            ArrayList billingAddressesList = new ArrayList();
            NewSalesOrderDAO.loadCustomerAddressesOfType(billingAddressesList, salesOrder.getCustomerId(), Constants.ADDRESS_TYPE_BILLING);
            salesOrder.setBillingAddresses ( billingAddressesList );

            session.setAttribute ( "allShippingTerms", subform.getAllShippingTerms () );
            session.setAttribute( "allDeliveryTerms", subform.getAllDeliveryTerms() );
            session.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );

            PropertyUtils.copyProperties ( subform, salesOrder );

            subform.setBillingContactPerson(salesOrder.getBillingContactPerson());
            subform.setShippingContactPerson(salesOrder.getShippingContactPerson());
            subform.setContactPerson(salesOrder.getContactPerson());
            if ( subform.getOdmId() > 0 )
            {
                salesOrder.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers( subform.getCustomerId (), subform.getOdmId(), isSample ) ) ;
                //salesOrder.setMfgPartsWithLabelNumbers( NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
                ArrayList contactPersons = subform.getContactPersons();
                contactPersons.add( subform.getCustomerName() );
                subform.setContactPersons(contactPersons);
                salesOrder.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) ) ;
                subform.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ));
                salesOrder.setOdmList( CustomerRelationshipDAO.getOdmsForChangeSalesOrder( salesOrder.getCustomerId()+"" , salesOrder.getOdmId()+"" ) );
            }
            else if ( ! "".equals( subform.getEndUser ().trim () ) )
            {
                subform.setEndUserId ( Integer.toString ( EndUserDAO.getEndUserIdByName ( subform.getEndUser (), subform.getCustomerId () ) ) );
                EndUser endUser = EndUserDAO.getEndUserDetails ( Integer.parseInt ( subform.getEndUserId () ) );
                session.setAttribute ( "mfgPartsWithCustomerPartNos", EndUserDAO.loadManfacturingPartNumbersWithEndUserPartNos ( Integer.parseInt ( subform.getEndUserId () ) ) );
                //session.setAttribute ( "mfgPartsWithLabelNumbers",EndUserDAO.loadManfacturingPartNumbersWithEndUserLabelNumbers ( Integer.parseInt ( subform.getEndUserId () ) ) );
                ArrayList<Address> shippingAddresses = endUser.getShippingLocations ();
                shippingAddresses.add ( 0, endUser.getShippingAddress () );
                shippingAddresses.add ( CustomerDAO.getAddress( SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId () ) ) );
                ArrayList contactPersons = subform.getContactPersons();
                contactPersons.add( subform.getCustomerName() );
                subform.setContactPersons(contactPersons);

                subform.setShippingAddresses ( loadShippingAddresses ( shippingAddresses ) );
                session.setAttribute ( "shippingAddresses", subform.getShippingAddresses () );
                session.setAttribute("salesPersons",CustomerDAO.loadAllSalesPersonsforCustomer(salesOrder.getCustomerId ()) ) ;
                subform.setShippingMethods( CustomerDAO.loadSalesOrderShippingMethods( subform.getCustomerId() ));
                session.setAttribute("odmList", CustomerRelationshipDAO.getAllOdmsForCustomer( salesOrder.getCustomerId ()+""));
            }
            else
            {
                salesOrder.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( salesOrder.getCustomerId (), subform.getOdmId(), isSample ) );
                //salesOrder.setMfgPartsWithLabelNumbers( NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( salesOrder.getCustomerId (), subform.getOdmId(), isSample ) );
                salesOrder.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer(salesOrder.getCustomerId ()) ) ;
                subform.setShippingMethods( CustomerDAO.loadSalesOrderShippingMethods( subform.getCustomerId() ));
                salesOrder.setOdmList( CustomerRelationshipDAO.getAllOdmsForCustomer( salesOrder.getCustomerId ()+""));
            }

            if ( salesOrder.getEndCustomerId() > 0 )
            {
                salesOrder.setEndCustomerList( CustomerRelationshipDAO.getEndCustomersForChangeSalesOrder( salesOrder.getCustomerId()+"" , salesOrder.getEndCustomerId()+"" ) );
            }
            else
            {
                salesOrder.setEndCustomerList( CustomerRelationshipDAO.getAllEndCustomersForCustomer( salesOrder.getCustomerId()+"" ) );
            }

            //Load the reason codes in request
            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );
            if ( subform.getShippingMethodName () != null )
            {
                subform.setShippingMethodName ( subform.getShippingMethodName ().trim () );
            }
            if ( subform.getShippingAccount () != null )
            {
                subform.setShippingAccount ( subform.getShippingAccount ().trim () );
            }
            request.setAttribute ( "Account", subform.getShippingMethodName () + "   #   " + subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingMethodName () + "   #   " + subform.getShippingAccount () );
            //Get the Holds for this orderId
            HashMap holds = SalesDAO.loadHoldsForOrder ( salesOrder.getSalesOrderId () );
            Iterator holdBy = holds.keySet ().iterator ();
            Iterator userBy = holds.values ().iterator ();
            //Loop thru the hold list and set the holds in the form
            while ( holdBy.hasNext () )
            {
                String holdedBy = ( String ) holdBy.next ();
                if ( holdedBy.equalsIgnoreCase ( "Finance" ) )
                {
                    subform.setFinanceHold ( true );
                    subform.setFinanceHoldUser ( ( String ) userBy.next () );
                }
                else if ( holdedBy.equalsIgnoreCase ( "Operations" ) )
                {
                    subform.setOperationsHold ( true );
                    subform.setOperationsHoldUser ( ( String ) userBy.next () );
                }
                else if ( holdedBy.equalsIgnoreCase ( "Sales" ) )
                {
                    subform.setSalesHold ( true );
                    subform.setSalesHoldUser ( ( String ) userBy.next () );
                }
                else if ( holdedBy.equalsIgnoreCase ( "Marketing" ) )
                {
                    subform.setMarketingHold ( true );
                    subform.setMarketingHoldUser ( ( String ) userBy.next () );
                }

            }
            ArrayList<LineItem> lineItems = SalesOrderDAO.loadAllChangeOrderLineItems ( null, salesOrder.getSalesOrderId () );

            for ( int i = 0; i < lineItems.size (); i++ )
            {
                LineItem templineItem = ( LineItem ) lineItems.get ( i );
                finalstatus = templineItem.getFinalStatus ();
            }
            //Load the staus of Sales order based on Line Item Status.
            status = SalesOrderDAO.loadSalesOrderStatus( null ,request.getParameter ( "salesOrderId" ) );
            subform.setStatus( status );

            request.setAttribute ( "salesOrderForm", subform );
            session.setAttribute ( "maxLineItemNo", Integer.toString ( SalesOrderDAO.loadMaxLineItemNo ( salesOrder.getSalesOrderId () ) ) );
            //Set the current order lineItems
            salesOrder.setPreviousLineItems( lineItems );

            session.setAttribute ( "presentLineItems", lineItems );
            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            //To get Customer PartNos of selected mfg part nos
            salesOrder.setMfgParts( SalesOrderDAO.loadAllManfacturingPartNosOfCustomerWithOutobsolete ( salesOrder.getCustomerId (), isSample ) );
            //salesOrder.setMfgPartsWithComments( SalesOrderDAO.loadAllManfacturingPartNumbersWithComments ( salesOrder.getCustomerId (), isSample ) );
            if (ConfigManager.getBooleanProperty(ConfigManager.PROP_SHOW_SALES_LINEITEM_BASE_ORDER_QTY) )
            {
                salesOrder.setMfgPartsWithBaseOrderQty( SalesOrderDAO.loadManufacturingPartNumbersWithBaseOrderQty ( null,  salesOrder.getSalesOrderId() ) ) ;
            }
            salesOrder.setSalesReps( CustomerDAO.loadAllSalesRepsforCustomer(salesOrder.getCustomerId ()) ) ;
            session.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
            session.setAttribute ( "freightInstructions", NewSalesOrderDAO.loadFreightInstructions( null ) );
            saveToken ( request );
            PropertyUtils.copyProperties ( salesOrder, subform );
            //return to the approver page, where approver can approve/reject
            return ( mapping.findForward ( "changeOrder" ) );
        }
        // Report any errors we have discovered back to the original form
        if ( !errors.isEmpty () )
        {
            request.setAttribute ( SessionKeys.MESSAGES, errors );
        }
        return ( mapping.findForward ( "successChange" ) );
    }

    private static ArrayList<LineItem> loadLineItems ( HttpServletRequest request, int customerId, HashMap<String, String> errors, HashMap<String, String> info, boolean checkLimits, int isSample ) throws ScalarException
    {
        String[] lineItemId = request.getParameterValues ( "lineItemId" );
        String[] lineItem = request.getParameterValues ( "lineItemNo" );
        String[] poLineItem = request.getParameterValues ( "poLineItemNo" );
        String[] manufacturingPartNo = request.getParameterValues ( "manufacturingPartNo" );
        String[] lineItemDescription = request.getParameterValues ( "lineItemDescription" );
        String[] quantity = request.getParameterValues("quantity");
        String[] oldQty = request.getParameterValues("oldQty");
        String[] requestDate = request.getParameterValues("requestDate");
        String[] unitPrice = request.getParameterValues("unitPriceAsDouble");
        String[] status = request.getParameterValues ( "statusq" );
        String[] oldStatus = request.getParameterValues ( "oldstatusq" );
        String[] finalStatus = request.getParameterValues ( "finalStatus" );
        String[] cancelStatus = request.getParameterValues ( "cancelStatus" );
        String[] issueStatus = request.getParameterValues ( "issueStatus" );
        String[] customerPartNo = request.getParameterValues ( "customerPartNo" );
        String[] scheduleDate = request.getParameterValues ( "scheduleDate" );
        String[] revisedDate = request.getParameterValues ( "revisedDate" );
        String[] customPriceField1 = request.getParameterValues ( "customPriceField1" );
        String[] customTextField1 = request.getParameterValues ( "customTextField1" );
        String[] isNewLineItem = request.getParameterValues ( "isNewLineItem" );
        String[] newCustPartNo = request.getParameterValues ( "newCustomerPartNo" );

        ArrayList<LineItem> lineItemsList = new ArrayList<LineItem> ();
        LineItem lineItemInfo = null;
        String zeroPrice = "";
        String productPrice = "";
        String cancelPatiallyShipped = "";
        String salesTaxType = request.getParameter ( "salesTaxType" );
        if ( ( salesTaxType.equalsIgnoreCase ( "-1" ) ) == true )
        {
            salesTaxType = request.getParameter ( "newSalesState" );
        }
        float taxvalue = SalesOrderDAO.getTaxValue ( null, salesTaxType );
        Float ff = new Float ( taxvalue );
        double tax = ff.doubleValue ();
        int totalQty = 0; double salesTax = 0.0;double finalSubTotal = 0.0;
        int tempLineItemNo = 0;
        for(int i=0; i<lineItem.length; i++)
        {
            if ( lineItem[i].trim ().equals ( "" ) )
            {
                lineItem[i] = "0";
            }
            if ( ( manufacturingPartNo[i] != null ) && ( !manufacturingPartNo[i].equals ( "" ) ) )
            {
                if ( quantity[i].equals ( "" ) )
                {
                    quantity[i] = "0";
                }

                if ( unitPrice[i].equals ( "" ) )
                {
                    unitPrice[i] = "0.0";
                }
                //For setting the PO line Item Number is 0 if it is empty
                if ( poLineItem[i].equals ( "" ) )
                {
                    poLineItem[i] = "0";
                }
                lineItemInfo = SalesOrderDAO.loadLineItemInfo ( customerId, Integer.parseInt ( lineItem[i] ),
                                                                null,
                                                                manufacturingPartNo[i],
                                                                requestDate[i],
                                                                Integer.parseInt ( quantity[i] ),
                                                                StringUtils.formatToFloat ( unitPrice[i] ),
                                                                status[i], isSample);
                //It is not a valid information entered, so add it errors
                if ( lineItemInfo == null )
                {
                    errors.put ( "LineItem No " + lineItem[i], "is not having valid partnumbers, please enter valid partnumbers" );
                }
                if ( lineItemInfo == null )
                {
                    lineItemInfo = new LineItem ();
                    lineItemInfo.setLineItemNo ( Integer.parseInt ( lineItem[i] ) );
                    lineItemInfo.setManufacturingPartNo ( manufacturingPartNo[i] );
                    lineItemInfo.setQuantity ( Integer.parseInt ( quantity[i] ) );
                    lineItemInfo.setUnitPrice ( StringUtils.formatToFloat ( unitPrice[i] ) );
                    lineItemInfo.setUnitPriceAsDouble ( Double.parseDouble ( unitPrice[i] ) );
                    lineItemInfo.setIsEditable ( true );
                    lineItemInfo.setRequestDate ( requestDate[i] );
                    lineItemInfo.setCustomerPartNo ( customerPartNo[i] );
                }
                else
                {
                    //Need to have the request date
                    if ( requestDate[i].trim ().length () == 0 )
                    {
                        errors.put ( "LineItem No " + lineItem[i], "Please enter Request Dock Date." );
                    }
                }
                lineItemInfo.setPoLineItemNo ( Integer.parseInt ( poLineItem[i] ) ); // Added by Basha (08/18/2003)
                zeroPrice = request.getParameter ( "zeroPrice" + ( lineItem[i] ) ); // Modified by Basha (08/20/2003)
                lineItemInfo.setZeroPrice ( ( zeroPrice != null ) ? true : false );
                //To set value to oldQty when it zero for the first time
                if ( "0".equals ( oldQty[i] ) )
                {
                    oldQty[i] = quantity[i];
                }
                productPrice = SalesOrderDAO.loadOldQtyPrice ( null, lineItemInfo.getProductId (), customerId, Integer.parseInt ( oldQty[i]), lineItemInfo.getRequestDate(), isSample);
                if ( ( ( Float.parseFloat ( unitPrice[i] ) != 0.0 ) || zeroPrice != null ) /*&& ( isSample == 1 )*/ )//sample orders may have unit price
                {
                    if ( ( quantity[i].equalsIgnoreCase ( oldQty[i] ) ) || ( !unitPrice[i].equalsIgnoreCase ( productPrice ) ) )
                    {
                        lineItemInfo.setUnitPrice(StringUtils.formatToFloat(Double.toString(Double.parseDouble(unitPrice[i]))));
						lineItemInfo.setUnitPriceAsDouble(Double.parseDouble(unitPrice[i]));
                        double unit_price = Double.parseDouble(unitPrice[i]);
                        double amt = (Integer.parseInt(quantity[i])) * unit_price;
						lineItemInfo.setAmountAsDouble(amt);
                    }
                }
                //we have moved whether sample SO is default to zero price or not to configuration..we may have price for sample orders.
                /*if ( isSample == 0)
                {
                    lineItemInfo.setUnitPrice ( 0 );
                    lineItemInfo.setUnitPriceAsDouble( 0 );
                    lineItemInfo.setAmount ( 0 );
                    lineItemInfo.setAmountAsDouble(0);
                }*/
                //For Cancel Check box functionality.
                if ( lineItemInfo.getOldStatus () == null )
                {
                    if ( oldStatus[i] == null )
                    {
                        lineItemInfo.setOldStatus ( lineItemInfo.getStatus () );
                    }
                    else
                    {
                        lineItemInfo.setOldStatus ( oldStatus[i] );
                    }
                }
                if ( cancelStatus[i] != null )
                {
                    lineItemInfo.setCancelStatus ( ( "0".equalsIgnoreCase ( cancelStatus[i] ) ) ? true : false );
                }
                if ( issueStatus[i] != null )
                {
                    lineItemInfo.setIssueStatus ( issueStatus[i] );
                }
                lineItemInfo.setIsExpedite ( ( request.getParameter ( "expediteFee" + i ) != null ) ? true : false );
                if ( request.getParameter ( "cancel" + i ) != null )
                {
                    lineItemInfo.setIsCancel ( true );
                    if ( "PARTIALLY SHIPPED".equalsIgnoreCase ( finalStatus[i] ) && !( lineItemInfo.getCancelStatus () ) )
                    {
                        cancelPatiallyShipped = cancelPatiallyShipped + lineItemInfo.getLineItemNo () + ",";
                    }
                    lineItemInfo.setStatus ( "Cancellation needs approval" );
                    request.setAttribute ( "CancelStatus", "False" );
                }
                else
                {
                    lineItemInfo.setIsCancel ( false );
                    lineItemInfo.setStatus ( oldStatus[i] );
                    request.setAttribute ( "Cancelstatus", "True" );
                }
                //Exception will throw when you use add more functinality,as there is no
                // LineItem id hidden field, catching the exception and setting lineItemId as -1
                try
                {
                    if ( lineItemId[i].trim ().length () != 0 )
                    {
                        lineItemInfo.setLineItemId ( Integer.parseInt ( lineItemId[i] ) );
                    }
                }
                catch ( ArrayIndexOutOfBoundsException aex )
                {
                    lineItemInfo.setLineItemId ( -1 );
                }

                if ( scheduleDate[i] != null && scheduleDate[i].trim ().length () > 0 )
                {
                    lineItemInfo.setScheduleDate (  scheduleDate[i]  );
                }
                if ( revisedDate[i] != null && revisedDate[i].trim ().length () > 0 )
                {
                    lineItemInfo.setRevisedDate (  revisedDate[i]  );
                }
                //calculate total quantity and amount and set it in request
                totalQty = totalQty + lineItemInfo.getQuantity();
				finalSubTotal = finalSubTotal + lineItemInfo.getAmountAsDouble();
                if ( request.getParameter ( "isTaxable" + lineItem[i] ) != null )
                {
                    lineItemInfo.setIsTaxable ( true );
                    salesTax = salesTax + (lineItemInfo.getAmountAsDouble() * (tax/100));
                }
                lineItemInfo.setLineItemDescription ( lineItemDescription[i] );
                lineItemInfo.setCustomerPartNo ( customerPartNo[i] );
                lineItemInfo.setNewCustomerPartNo ( newCustPartNo[i] );
                lineItemInfo.setCustomPriceField1(customPriceField1!= null ? Double.parseDouble(customPriceField1[i]) : 0);
                lineItemInfo.setCustomTextField1(customTextField1 != null ? customTextField1[i] : null);
                lineItemInfo.setFinalStatus(finalStatus[i]);
                request.setAttribute("totalQty",Integer.toString(totalQty));
                request.setAttribute("salesTax",Double.toString(salesTax));
				request.setAttribute("subTotal",Double.toString(finalSubTotal) );
                if ( isNewLineItem[i].equalsIgnoreCase ( "true" ) )
                {
                    lineItemInfo.setIsNewLineItem ( true );
                }
                else
                {
                    lineItemInfo.setIsNewLineItem ( false );
                }
                //To calculate the maxLineItemNo
                if(Integer.parseInt(lineItem[i]) > tempLineItemNo )
                {
                    tempLineItemNo = Integer.parseInt(lineItem[i]);
                }
                lineItemsList.add ( lineItemInfo );
            }
        }
        request.setAttribute ( "maxLineItemNo", Integer.toString ( tempLineItemNo + 1 ) );

        if ( cancelPatiallyShipped != null && !( "".equals ( cancelPatiallyShipped ) ) )
        {
            cancelPatiallyShipped = cancelPatiallyShipped.substring ( 0, cancelPatiallyShipped.length () - 1 );
            info.put ( "Are you sure you want to cancel the remaining quantity of the partially shipped line item(s):&nbsp;" + cancelPatiallyShipped, null );
        }

        request.setAttribute ( "Errors", errors );
        request.setAttribute ( "Info", info );
        return lineItemsList;
    }

    //For getting the summary of changes made to the sales order
    public String getSalesOrderChangeSummary ( DBTransaction dbTransaction, SalesOrder newSalesOrder, SalesOrder oldSalesOrder ) throws ScalarException
    {
        StringBuffer changeSummary = new StringBuffer ( "" );
        try
        {
            if ( oldSalesOrder != null && newSalesOrder != null )
            {
                if ( oldSalesOrder.getCustomerPO() == null )
                {
                    oldSalesOrder.setCustomerPO ( "" );
                }
                if ( oldSalesOrder.getReason() == null )
                {
                    oldSalesOrder.setReason( "" );
                }
                if ( oldSalesOrder.getContactPerson () == null )
                {
                    oldSalesOrder.setContactPerson( "" );
                }
                if ( oldSalesOrder.getBillingContactPerson() == null )
                {
                    oldSalesOrder.setBillingContactPerson( "" );
                }
                if ( oldSalesOrder.getShippingContactPerson() == null )
                {
                    oldSalesOrder.setShippingContactPerson( "" );
                }
                if ( oldSalesOrder.getPoRev() == null )
                {
                    oldSalesOrder.setPoRev( "" );
                }
                if ( oldSalesOrder.getSalesPerson() == null )
                {
                    oldSalesOrder.setSalesPerson( "" );
                }
                if ( oldSalesOrder.getShippingTerms() == null )
                {
                    oldSalesOrder.setShippingTerms( "" );
                }
                if ( oldSalesOrder.getShippingMethod() == null )
                {
                    oldSalesOrder.setShippingMethod( "" );
                }
                if ( oldSalesOrder.getShippingAccount() == null )
                {
                    oldSalesOrder.setShippingAccount( "" );
                }
                if ( oldSalesOrder.getShippingTerms() == null )
                {
                    oldSalesOrder.setShippingTerms( "" );
                }
                if ( oldSalesOrder.getDeliveryTerms() == null )
                {
                    oldSalesOrder.setDeliveryTerms( "" );
                }
                if ( oldSalesOrder.getRegionalRep() == null )
                {
                    oldSalesOrder.setRegionalRep( "" );
                }
                if ( oldSalesOrder.getEndUser() == null )
                {
                    oldSalesOrder.setEndUser( "" );
                }
                if ( oldSalesOrder.getComments() == null )
                {
                    oldSalesOrder.setComments( "" );
                }
                if ( oldSalesOrder.getFreightInstructions() == null )
                {
                    oldSalesOrder.setFreightInstructions( "" );
                }
                if ( oldSalesOrder.getShippingInstructions () == null )
                {
                    oldSalesOrder.setShippingInstructions( "" );
                }
                if ( oldSalesOrder.getSalesTaxType() == null )
                {
                    oldSalesOrder.setSalesTaxType( "" );
                }
                if ( newSalesOrder.getCustomerPO() == null )
                {
                    newSalesOrder.setCustomerPO( "" );
                }
                if ( newSalesOrder.getReason() == null )
                {
                    newSalesOrder.setReason( "" );
                }
                if ( newSalesOrder.getContactPerson () == null )
                {
                    newSalesOrder.setContactPerson ( "" );
                }
                if ( newSalesOrder.getBillingContactPerson () == null )
                {
                    newSalesOrder.setBillingContactPerson( "" );
                }
                if ( newSalesOrder.getShippingContactPerson() == null )
                {
                    newSalesOrder.setShippingContactPerson( "" );
                }
                if ( newSalesOrder.getSalesPerson() == null )
                {
                    newSalesOrder.setSalesPerson( "" );
                }
                if ( newSalesOrder.getShippingMethod() == null )
                {
                    newSalesOrder.setShippingMethod( "" );
                }
                if ( newSalesOrder.getShippingAccount() == null )
                {
                    newSalesOrder.setShippingAccount( "" );
                }
                if ( newSalesOrder.getDeliveryTerms() == null )
                {
                    newSalesOrder.setDeliveryTerms( "" );
                }
                if ( newSalesOrder.getRegionalRep() == null )
                {
                    newSalesOrder.setRegionalRep( "" );
                }
                if ( newSalesOrder.getEndUser() == null )
                {
                    newSalesOrder.setEndUser( "" );
                }
                if ( newSalesOrder.getComments() == null )
                {
                    newSalesOrder.setComments( "" );
                }
                if ( newSalesOrder.getShippingInstructions () == null )
                {
                    newSalesOrder.setShippingInstructions( "" );
                }
                if ( newSalesOrder.getSalesTaxType() == null )
                {
                    newSalesOrder.setSalesTaxType( "" );
                }
                if ( !oldSalesOrder.getCustomerPO().equals ( newSalesOrder.getCustomerPO() ) )
                {
                    changeSummary.append ( "<br> Customer PO  has been changed " );
                }

                if ( !oldSalesOrder.getContactPerson().equals ( newSalesOrder.getContactPerson() ) )
                {
                    changeSummary.append ( "<br> Contact Person has been changed " );
                }
                if ( !oldSalesOrder.getPoRev().equals ( newSalesOrder.getPoRev() ) )
                {
                    String poRevLabel = null;
                    try
                    {
                        poRevLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.PoRevisionNumber" );
                        if ( poRevLabel == null )
                        {
                            poRevLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        poRevLabel  = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                    changeSummary.append ( "<br>"+poRevLabel+" has been changed " );
                }
                if ( !oldSalesOrder.getPoDate().equals ( newSalesOrder.getPoDate() ) )
                {
                    String poDateLabel = null;
                    try
                    {
                        poDateLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.PoDate" );
                        if ( poDateLabel == null )
                        {
                            poDateLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        poDateLabel  = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                    changeSummary.append ( "<br>"+poDateLabel+" has been changed " );
                }
                if ( !oldSalesOrder.getSalesPerson ().equals ( newSalesOrder.getSalesPerson () ) )
                {
                    changeSummary.append ( "<br> Sales Person has been changed " );
                }
                if ( !oldSalesOrder.getSalesRep ().equals ( newSalesOrder.getSalesRep () ) )
                {
                    String representativeLabel = null;
                    try
                    {
                        representativeLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesRep.Name" );
                        if ( representativeLabel == null )
                        {
                            representativeLabel = Labels.DEFAULT_REPRESENTATIVE;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        representativeLabel = Labels.DEFAULT_REPRESENTATIVE;
                    }
                    changeSummary.append ( "<br> "+representativeLabel+" has been changed " );
                }
                if ( !oldSalesOrder.getShippingMethod ().equals ( newSalesOrder.getShippingMethod () ) )
                {
                    String shippingMethodLabel = null;
                    try
                    {
                        shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                        if ( shippingMethodLabel == null )
                        {
                            shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                    changeSummary.append ( "<br> "+shippingMethodLabel+"  has been changed " );
                }
                if ( !oldSalesOrder.getShippingAccount ().equals ( newSalesOrder.getShippingAccount () ) )
                {
                    String shippingAccountLabel = null;
                     try
                    {
                        shippingAccountLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingAccount" );
                        if ( shippingAccountLabel == null )
                        {
                            shippingAccountLabel = Labels.DEFAULT_SHIPPING_ACCOUNT_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        shippingAccountLabel = Labels.DEFAULT_SHIPPING_ACCOUNT_LABEL;
                    }
                    changeSummary.append ( "<br>"+shippingAccountLabel+" has been changed " );
                }
                if ( !oldSalesOrder.getShippingTerms ().equals ( newSalesOrder.getShippingTerms () ) )
                {
                    changeSummary.append ( "<br> Pay Terms  have been changed " );
                }
                if ( !oldSalesOrder.getDeliveryTerms ().equals ( newSalesOrder.getDeliveryTerms () ) )
                {
                    String deliveryTermsLabel = null;
                    try
                    {
                        deliveryTermsLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.DeliveryTerms" );
                        if ( deliveryTermsLabel == null )
                        {
                            deliveryTermsLabel = Labels.DEFAULT_DELIVERY_TERMS_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        deliveryTermsLabel    = Labels.DEFAULT_DELIVERY_TERMS_LABEL;
                    }
                    changeSummary.append ( "<br>"+deliveryTermsLabel+"  have been changed " );
                }
                if ( !oldSalesOrder.getRegionalRep ().equals ( newSalesOrder.getRegionalRep () ) )
                {
                    changeSummary.append ( "<br> Regional Rep  has been changed " );
                }
                if ( oldSalesOrder.getBookingDate ().compareTo ( newSalesOrder.getBookingDate () ) != 0 )
                {
                    changeSummary.append ( "<br> Booking Date  has been changed " );
                }
                if ( !oldSalesOrder.getEndCustomer().equals ( newSalesOrder.getEndCustomer() ) )
                {
                    String endUserLabel = null;
                    try
                    {
                        endUserLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endUser" );
                        if ( endUserLabel == null )
                        {
                            endUserLabel = Labels.DEFAULT_END_USER_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        endUserLabel    = Labels.DEFAULT_END_USER_LABEL;
                    }
                    changeSummary.append ( "<br> " + endUserLabel + " has been changed " );
                }
                if ( !oldSalesOrder.getOdm().equals ( newSalesOrder.getOdm() ) )
                {
                    String endCustomerLabel = null;
                    try
                    {
                        endCustomerLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endCustomer" );
                        if ( endCustomerLabel == null )
                        {
                            endCustomerLabel = Labels.DEFAULT_END_CUSTOMER_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        endCustomerLabel    = Labels.DEFAULT_END_CUSTOMER_LABEL;
                    }
                    changeSummary.append ( "<br> " + endCustomerLabel + " has been changed " );
                }
                if ( !oldSalesOrder.getBillingContactPerson ().equals ( newSalesOrder.getBillingContactPerson () ) )
                {
                    changeSummary.append ( "<br> Billing Contact Person has been changed " );
                }
                if ( !oldSalesOrder.getShippingContactPerson ().equals ( newSalesOrder.getShippingContactPerson () ) )
                {
                    changeSummary.append ( "<br> Shipping Contact Person has been changed " );
                }
                if ( oldSalesOrder.getShippingAddressId () != newSalesOrder.getShippingAddressId () )
                {
                    changeSummary.append ( "<br> Shipping Address  has been changed " );
                }
                if ( oldSalesOrder.getBillingAddressId () != newSalesOrder.getBillingAddressId () )
                {
                    changeSummary.append ( "<br> Billing Address  has been changed " );
                }
                if ( !oldSalesOrder.getComments ().equals ( newSalesOrder.getComments () ) )
                {
                    changeSummary.append ( "<br> Comments  have been changed " );
                }
                if ( !oldSalesOrder.getFreightInstructions().equals ( newSalesOrder.getFreightInstructions() ) )
                {
                    changeSummary.append ( "<br> Freight Instructions have been changed " );
                }
                if ( !oldSalesOrder.getShippingInstructions ().equals ( newSalesOrder.getShippingInstructions () ) )
                {
                    changeSummary.append ( "<br> Shipping Instructions have been changed " );
                }
                if ( !oldSalesOrder.getSalesTaxType ().equals ( newSalesOrder.getSalesTaxType () ) )
                {
                    changeSummary.append ( "<br> Sales Tax type has been changed " );
                }
                if ( oldSalesOrder.getMisc () != newSalesOrder.getMisc () )
                {
                    changeSummary.append ( "<br> Misc amount has been changed " );
                }
                if ( oldSalesOrder.getFrieght () != newSalesOrder.getFrieght () )
                {
                    changeSummary.append ( "<br> Frieght amount has been changed " );
                }
            }
        }
        catch ( Exception se )
        {
            se.printStackTrace ();
            throw new ScalarException ( "Error while comparing the sales orders ", se );
        }
        return changeSummary.toString ();
    }

    private void addNewSalesTaxState ( HttpServletRequest request, HttpSession session, HashMap<String, String> errors, SalesOrderForm subform )
    {
        String state1 = null;
        String value1 = null;
        String[] newSalesState = new String[1];
        String[] newSalesTax = new String[1];
        boolean checkstate = false;

        try
        {
            state1 = request.getParameter ( "newSalesState" );
            value1 = request.getParameter ( "newSalesTax" );
            String salesTaxType = request.getParameter ( "salesTaxType" );
            if ( "-1".equals ( salesTaxType ) )
            {
                if ( state1 != null )
                {
                    state1 = state1.trim ();
                }
                checkstate = SalesOrderDAO.doesSalesTaxStateExist ( null, state1 );

                if ( checkstate == false )
                {

                    if ( ( state1 != null && state1.length () > 0 ) && ( value1 != null && value1.length () > 0 ) )
                    {

                        newSalesState[0] = state1.trim ();
                        newSalesTax[0] = value1.trim ();

                        SalesDAO.saveSalesTaxes ( newSalesState, newSalesTax, " " );
                        ArrayList<LabelValueBean> salesStatesList = ( ArrayList<LabelValueBean> ) session.getAttribute ( "salesTaxes" );

                        salesStatesList.add ( new org.apache.struts.util.LabelValueBean ( state1 + " - " + value1, state1 ) );
                        session.setAttribute ( "salesTaxes", salesStatesList );
                        subform.setSalesTaxType ( state1 );
                        value1 = null;
                    }//if
                }//if
                else
                {
                    errors.put ( "The State '" + state1 + "' already exists", null );
                    request.setAttribute ( "otherstateadded", "false" );
                    request.setAttribute ( "newsalesstate", state1 );
                    request.setAttribute ( "newsalesvalue", value1 );
                }
            }

        }//try
        catch ( Exception e )
        {
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_NEW_SALES_TAX_STATE );
            errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
            session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save New Sales Tax State" );
            session.setAttribute ( SessionKeys.ERROR_REPORT, e );
        }
        request.setAttribute ( "Errors", errors );
    }//end of method addNewSalesTaxState

    //To optimise code for adding New Shipping Method which is used more than once
    private void addNewShippingMethod ( HttpServletRequest request, HttpSession session, HashMap<String, String> errors, HashMap<String, String> info, SalesOrderForm subform, SalesOrder salesOrderFromMap )
    {
        String customerId = request.getParameter ( "customerId" );
        String method = null;
        String account = null;
        String newShippingMethodLabel = null;
        String shippingMethodLabel = null;
        boolean checkmethodexist = true;
        int customerIdvalue = -1;

        if ( customerId != null )
        {
            session.setAttribute ( "addShippingMethodCustomerId", customerId );
        }
        else
        {
            customerId = ( String ) session.getAttribute ( "addShippingMethodCustomerId" );
        }

        String shippingMethod = subform.getShippingMethod ();
        if ( "-2".equalsIgnoreCase ( shippingMethod ) == true )
        {
            try
            {
                method = request.getParameter ( "newshippingMethod" );
                account = request.getParameter ( "newshippingAccount" );
                customerIdvalue = Integer.parseInt ( customerId );
                if ( method != null )
                {
                    method = method.trim ();
                }
                if ( account != null )
                {
                    account = account.trim ();
                }
                checkmethodexist = CustomerDAO.doesShippingMethodExist ( null, customerIdvalue, method, account );
                if ( checkmethodexist == false )
                {
                    if ( !( ( method.equals ( "" ) ) && ( account.equals ( "" ) ) ) )
                    {
                        try
                        {
                            if ( method != null )
                            {
                                method = method.trim ();
                            }
                            if ( account != null )
                            {
                                account = account.trim ();
                            }
                            CustomerDAO.insertShippingMethod ( null, customerIdvalue, method, account );
                            ArrayList<LabelValueBean> shippingMethodList = salesOrderFromMap.getShippingMethods();
                            //To get shiping account along with shipping method
                            shippingMethodList.add ( new org.apache.struts.util.LabelValueBean ( method + "   #   " + account, method + "   #   " + account ) );
                            salesOrderFromMap.setShippingMethods( shippingMethodList );

                            //For removing the values from new shippoing method and account after they have been added to the database
                            subform.setNewshippingAccount ( "" );
                            subform.setNewshippingMethod ( "" );
                            try
                            {
                                newShippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.NewShippingMethod" );
                                if ( newShippingMethodLabel == null )
                                {
                                    newShippingMethodLabel = Labels.DEFAULT_NEW_SHIPPING_METHOD_LABEL;
                                }
                            }
                            catch ( NullPointerException e )
                            {
                                 newShippingMethodLabel = Labels.DEFAULT_NEW_SHIPPING_METHOD_LABEL;
                            }
                            info.put ( newShippingMethodLabel+" has been stored in database successfully", null );
                        }

                        catch ( ScalarException se )
                        {
                            try
                            {
                                shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                                if ( shippingMethodLabel == null )
                                {
                                    shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                                }
                            }
                            catch ( NullPointerException e )
                            {
                                shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                            }
                            errors.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not Save "+shippingMethodLabel+" Value."+method );
                            se.printStackTrace ();
                        }
                    }//if
                    subform.setShippingMethodName ( method + "   #   " + account );
                    subform.setShippingAccount ( method + "   #   " + account );
                    subform.setShippingMethod ( method + "   #   " + account );
                    salesOrderFromMap.setShippingMethod( subform.getShippingMethod() );
                }
                else
                {
                    try
                    {
                        shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                        if ( shippingMethodLabel == null )
                        {
                            shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                    errors.put ( method + shippingMethodLabel+" already Exists ,Please enter another "+shippingMethodLabel+".", null );
                }
            }
            catch ( Exception e )
            {
                e.printStackTrace ();
            }
        }
    }
    private void addNewShippingTerms ( HttpServletRequest request, HttpSession session, HashMap<String,String> errors, HashMap<String,String> info, SalesOrderForm subform )
    {
        String shippingTerms = null;
        String newShippingTerms = null;
        boolean checkmethodexist = true;

        shippingTerms = subform.getShippingTerms ();
        if ( "-2".equalsIgnoreCase ( shippingTerms ) == true )
        {
            try
            {
                newShippingTerms = request.getParameter ( "newShippingTerms" );
                if ( newShippingTerms != null )
                {
                    newShippingTerms = newShippingTerms.trim ();
                }
                else
                {
                    newShippingTerms = "";
                }
                if ( newShippingTerms != null && newShippingTerms.trim ().length () != 0 )
                {
                    checkmethodexist = SalesDAO.doesShippingTermsExist ( null, newShippingTerms );

                    if( Constants.CLIENT_NAME_AIRGO.equalsIgnoreCase( ConfigManager.getClientNameAirgo() ) && Constants.SALESORDER_LETTER_OF_CREDIT.equalsIgnoreCase ( newShippingTerms ) )
                    {
                        checkmethodexist = true;
                    }
                    if ( checkmethodexist == false )
                    {
                        try
                        {
                            SalesDAO.insertShippingTerms ( null, newShippingTerms );
                            ArrayList shippingTermsList = ( ArrayList ) session.getAttribute ( "allShippingTerms" );
                            shippingTermsList.add ( newShippingTerms );
                            session.setAttribute ( "allShippingTerms", shippingTermsList );
                            info.put ( "New Pay Terms are added successfully", null );
                            subform.setShippingTerms ( newShippingTerms );
                        }
                        catch ( ScalarException se )
                        {
                            String shippingMethodLabel = null;
                            try
                            {
                                shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                                if ( shippingMethodLabel == null )
                                {
                                    shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                                }
                            }
                            catch ( NullPointerException e )
                            {
                                shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                            }
                            errors.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not Save "+shippingMethodLabel+" Value."+ newShippingTerms );
                            se.printStackTrace ();
                        }
                    }
                    else
                    {
                        errors.put ( newShippingTerms + " " + ERROR_SHIPPING_TERMS_EXISTS, null );
                    }
                }
            }
            catch ( Exception e )
            {
                e.printStackTrace ();
            }

        }
        if( Constants.CLIENT_NAME_AIRGO.equalsIgnoreCase( ConfigManager.getClientNameAirgo() ) )
        {
            if( ! Constants.SALESORDER_LETTER_OF_CREDIT.equalsIgnoreCase ( subform.getShippingTerms() ) )
            {
                subform.setLetterOfCreditNo( null );
                subform.setLcIssuingBank( null );
            }
        }
        else
        {
            subform.setLetterOfCreditNo( null );
            subform.setLcIssuingBank( null );
        }
    }

    private ArrayList<LabelValueBean> loadShippingAddresses ( ArrayList<Address> shippingAddresses )
    {
        Address address = null;
        ArrayList<LabelValueBean> shippingList = new ArrayList<LabelValueBean>();
        for ( int i = 0; i < shippingAddresses.size (); i++ )
        {
            address = ( Address ) shippingAddresses.get ( i );

            String addrStr = "";
            if ( ( address.getAddress1 () != null ) && ( address.getAddress1 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new LabelValueBean ( address.getAddress1 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress2 () != null ) && ( address.getAddress2 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new LabelValueBean ( address.getAddress2 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress3 () != null ) && ( address.getAddress3 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new LabelValueBean ( address.getAddress3 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress4 () != null ) && ( address.getAddress4 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new LabelValueBean ( address.getAddress4 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getCity () != null ) && ( address.getCity ().trim ().length () != 0 ) )
            {
                shippingList.add ( new LabelValueBean ( address.getCity (), Integer.toString ( address.getAddressId () ) ) );
            }

            if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
            {
                addrStr = addrStr + address.getState ();
            }
            if ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) )
            {
                if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
                {
                    addrStr = addrStr + "-";
                }

                addrStr = addrStr + address.getZipCode ();
            }
            if ( ( address.getCountry () != null ) && ( address.getCountry ().trim ().length () != 0 ) )
            {
                if ( ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) ) || ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) ) )
                {
                    addrStr = addrStr + ",";
                }
                addrStr = addrStr + address.getCountry ();
            }
            if ( !( "".equals ( addrStr ) ) )
            {
                shippingList.add ( new LabelValueBean ( addrStr, Integer.toString ( address.getAddressId () ) ) );
            }
            //For dispalying a line after each address
            shippingList.add ( new LabelValueBean ( "", Integer.toString ( address.getAddressId () ) ) );
        }
        //Set all the shippingAddresses in the salesOrder
        return shippingList;
    }

    public static void loadShippingAddress( Address address, ArrayList<LabelValueBean> shippingList, SalesOrder salesOrderFromMap )
    {

        String addrStr = "";

        if ( ( address.getAddress1 () != null ) && ( address.getAddress1 ().trim ().length () != 0 ) )
        {
            shippingList.add ( new LabelValueBean ( address.getAddress1 (), Integer.toString ( address.getAddressId () ) ) );
        }
        if ( ( address.getAddress2 () != null ) && ( address.getAddress2 ().trim ().length () != 0 ) )
        {
            shippingList.add ( new LabelValueBean ( address.getAddress2 (), Integer.toString ( address.getAddressId () ) ) );
        }
        if ( ( address.getAddress3 () != null ) && ( address.getAddress3 ().trim ().length () != 0 ) )
        {
            shippingList.add ( new LabelValueBean ( address.getAddress3 (), Integer.toString ( address.getAddressId () ) ) );
        }
        if ( ( address.getAddress4 () != null ) && ( address.getAddress4 ().trim ().length () != 0 ) )
        {
            shippingList.add ( new LabelValueBean ( address.getAddress4 (), Integer.toString ( address.getAddressId () ) ) );
        }
        if ( ( address.getCity () != null ) && ( address.getCity ().trim ().length () != 0 ) )
        {
            shippingList.add ( new LabelValueBean ( address.getCity (), Integer.toString ( address.getAddressId () ) ) );
        }
        if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
        {
            addrStr = addrStr + address.getState ();
        }
        if ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) )
        {
            if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
            {
                addrStr = addrStr + "-";
            }
            addrStr = addrStr + address.getZipCode ();
        }
        if ( ( address.getCountry () != null ) && ( address.getCountry ().trim ().length () != 0 ) )
        {
            if ( ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) ) || ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) ) )
            {
                addrStr = addrStr + ",";
            }
            addrStr = addrStr + address.getCountry ();
        }
        if ( !( "".equals ( addrStr ) ) )
        {
            shippingList.add ( new LabelValueBean ( addrStr, Integer.toString ( address.getAddressId () ) ) );
        }
        shippingList.add ( new LabelValueBean ( "", Integer.toString ( address.getAddressId () ) ) );
        ArrayList<String> shippingContactPersons = new ArrayList<String>();
        shippingContactPersons.add( address.getContactPerson() );
        salesOrderFromMap.setContactPersonsForShippingAddress( shippingContactPersons );
    }


    public static String finalstatus = null;

    public static String getAddressAsString(Address address)
    {
        StringBuffer tempAddress =   new StringBuffer("");
        String address1 = address.getAddress1();
        String address2 = address.getAddress2();
        String address3 = address.getAddress3();
        String address4 = address.getAddress4();
        String city = address.getCity();
        String zipCode= address.getZipCode();
        String state = address.getState();
        String country = address.getCountry();

        if(address1!=null && !(address1.trim().equals("")))
        {
            tempAddress.append(address1);
        }
        if(address2!=null && !(address2.equals("")))
        {
            tempAddress.append(address2);
        }
        if(address3!=null && !(address3.equals("")))
        {
           tempAddress.append(address3);
        }
        if(address4!=null && !(address4.equals("")))
        {
           tempAddress.append(address4);
        }
        if(city!=null && !(city.equals("")))
        {
            tempAddress.append(city);
        }
        if(state!=null && !(state.equals("")))
        {
            tempAddress.append(state);
        }
        if(zipCode!=null && !(zipCode.equals("")))
        {
            tempAddress.append(zipCode);
        }
        if(country!=null && !(country.equals("")))
        {
            tempAddress.append(country);
        }
        return tempAddress.toString();
    }

    //Returns the javascript generated using the hashMap and scriptVariable.
    public static String getMapScript ( HashMap hashMap, String scriptVariable, boolean keysRequired )
    {
        StringBuffer buffer = new StringBuffer ();
        StringBuffer keyBuffer = new StringBuffer ();
        try
        {   if ( hashMap == null )
            {
                return keyBuffer.toString();
            }
            java.util.Iterator mapKeyIterator = hashMap.keySet ().iterator ();
            int count = 0;
            if ( keysRequired )
            {
                keyBuffer.append ( "\n" + "var keys = new Array();\n" );
            }

            keyBuffer.append ( "\n" + "var " + scriptVariable + " = new Array();\n" );
            if("customernos".equalsIgnoreCase( scriptVariable ) )
            {
                while ( mapKeyIterator.hasNext () )
                {
                    Object key = mapKeyIterator.next ();
                    if ( keysRequired )
                    {
                        keyBuffer.append ( "keys[" ).append ( count ).append ( "]='" ).append ( key ).append ( "';\n" );
                    }
                    buffer.append ( scriptVariable + "[" + count + "]=new Array(" );
                    if ( hashMap.get ( key ) != null )
                    {
                       ArrayList custpartsList = (ArrayList)hashMap.get(key);
                       for( int i=0; i< custpartsList.size(); i++ )
                        {
                            buffer.append("\"").append(custpartsList.get(i)).append("\"");
                            if( i+1 != custpartsList.size() )
                            {
                                buffer.append(",");
                            }
                        }

                    }
                    buffer.append ( ");\n" );
                    count++;
                }
                keyBuffer.append ( buffer );
            }
            else
            {
                while ( mapKeyIterator.hasNext () )
                {
                    Object key = mapKeyIterator.next ();
                    if ( keysRequired )
                    {
                        keyBuffer.append ( "keys[" ).append ( count ).append ( "]='" ).append ( key ).append ( "';\n" );
                    }
                    buffer.append ( scriptVariable + "[" + count + "]='" );
                    if ( hashMap.get ( key ) != null )
                    {
                        buffer.append ( StringUtils.escapeSpecialString(( String ) hashMap.get ( key )));
                    }
                    buffer.append ( "';\n" );
                    count++;
                }
                keyBuffer.append ( buffer );
            }
        }
        catch ( Exception e )
        {
            e.printStackTrace ();
        }
        return keyBuffer.toString ();
    }
}
